
clear all
*set-up
cd "E:\workdata\702992\702992\Matias"
version 16.1
set scheme plotplain
graph set window fontface "Times New Roman"
set graphic off

****************************************************************************************
********************SET UP PANEL DATA ANALYSIS****************************************
****************************************************************************************
if 1==1 {
frame rename default panelanalysis    

use "E:\workdata\702992\702992\Matias\inequalitypanel\Poor_rich_dofiles\mainpanelsample.dta",clear

*Globals for variables/specifications
global IV "indkomstplac20"
global ICOVAR "yearslived EduYearsRS hhi_ln statsborgerskab_RS i.unemployed_RS i.civilstand i.samboende i.wave"
global ICOVARa "koenRS alderRS yearslived EduYearsRS statsborgerskab_RS i.oprindelse i.unemployed_RS i.civilstand i.samboende "
global ICOVARudenyears "EduYearsRS hhi_ln statsborgerskab_RS i.unemployed_RS i.civilstand i.samboende i.wave"

global depvar1 redist

global afst 100 150 200 250 500 1000 1500 2000 2500 //radii
global CCOVAR  agespread_ unempl_narrow_ medianinc_ ethdiv_ enligfors_  residentialturnover_ neigh_ //contextual controls

foreach dist of global afst {
	foreach cc of global CCOVAR {
		local ccovar`dist'  "`ccovar`dist'' `cc'`dist'"
	}
	global ccovar`dist' "`ccovar`dist''"
}

****Creating dataframe with ess1 and ess2 respondents
frame create fullpanel
frame change fullpanel
use "E:\workdata\702992\702992\Matias\inequalitypanel\Poor_rich_dofiles\panelsample_ess1_ess2.dta",clear


}

****************************************************************************************
********************SET UP CROSS-SECTIONAL ANALYSIS*************************************
****************************************************************************************
if 1==1 {
frame create cross_analysis
frame change cross_analysis

use "E:\workdata\702992\702992\Matias\inequalitypanel\Poor_rich_dofiles\cross_sectional_sample.dta",clear


*Globals for variables/specifications
global IV "indkomstplac20"
global ICOVAR_cross "koenRS alderRS yearslived hhi_ln EduYearsRS statsborgerskab_RS i.oprindelse i.unemployed_RS i.civilstand i.samboende i.survey"
global ICOVAR_cross_ideo "koenRS alderRS yearslived hhi_ln EduYearsRS statsborgerskab_RS i.oprindelse i.unemployed_RS i.civilstand i.samboende i.survey gammelskala"
global ICOVARa_cross "i.koenRS alderRS yearslived EduYearsRS statsborgerskab_RS i.oprindelse i.unemployed_RS i.civilstand i.samboende"
global depvar1 redist

global afst 100 150 200 250 500 1000 1500 2000 2500 //radii


}


frame change panelanalysis

****************************************************************************************
********************ANALYSIS****************************************
****************************************************************************************
if 1==1 {

capture log close //closing log-files
log using ".\inequalitypanel\results\mainanalyse", text replace 
frame change panelanalysis

****************************************************************************
****************TABLE A8************************************************
********************************************************************************
if 1==1 {
	foreach dist in 100  {
	*******WITHOUT CONTROLVARIABLES AND UNCONDITIONAL
	xtreg redist indkomstplac20`dist' i.wave if prim_sample==1, fe robust
	estadd local Waves "Three"
	estadd local IFE "\checkmark"
	estadd local WFE "\checkmark"
	estadd local MuniFE "$-$"
	estadd local IC "$-$"
	estadd local CC "$-$"
	matrix N_g = e(N_g)
	local Individual = N_g[1,1]
	estadd local Individual `Individual'
	est store Model1a
	
	*******WITHOUT CONTROLVARIABLES AND CONDITIONAL		
	xtreg redist indkomstplac20`dist' c.indkomstplac20`dist'#place_primsample i.wave if prim_sample==1, fe robust
	estadd local Waves "Three"
	estadd local IFE "\checkmark"
	estadd local WFE "\checkmark"
	estadd local MuniFE "$-$"
	estadd local IC "$-$"
	estadd local CC "$-$"
	matrix N_g = e(N_g)
	local Individual = N_g[1,1]
	estadd local Individual `Individual'
	est store Model1b
	
	***Marginal effects for table****
	eststo m1: margins, dydx(indkomstplac20`dist') at(place_primsample=(0 1 2 3 4)) post

	*******WITH CONTROLVARIABLES AND UNCONDITIONAL
	xtreg redist indkomstplac20`dist' $ICOVAR  ${ccovar`dist'} i.municip if prim_sample==1, fe robust
	estadd local Waves "Three"
	estadd local IFE "\checkmark"
	estadd local WFE "\checkmark"
	estadd local MuniFE "\checkmark"
	estadd local IC "\checkmark"
	estadd local CC "\checkmark"
		matrix N_g = e(N_g)
	local Individual = N_g[1,1]
	estadd local Individual `Individual'
	est store Model1c
	
 	*******WITH CONTROLVARIABLES AND CONDITIONAL		
	xtreg redist indkomstplac20`dist' c.indkomstplac20`dist'#place_primsample  $ICOVAR  ${ccovar`dist'} i.municip if prim_sample==1, fe robust
	estadd local Waves "Three"
	estadd local IFE "\checkmark"
	estadd local WFE "\checkmark"
	estadd local MuniFE "\checkmark"
	estadd local IC "\checkmark"
	estadd local CC "\checkmark"
		matrix N_g = e(N_g)
	local Individual = N_g[1,1]
	estadd local Individual `Individual'
	est store Model1d
	
	***Marginal effects for table****
	eststo m2: margins, dydx(indkomstplac20`dist') at(place_primsample=(0 1 2 3 4)) post
	
	 *******WITH CONTROLVARIABLES AND SHARE OF RICH
	xtreg redist indkomstplac20`dist' c.indkomstplac20`dist'#place_primsample indkomstplac80`dist' c.indkomstplac80`dist'#place_primsample $ICOVAR  ${ccovar`dist'} i.municip if prim_sample==1, fe robust
	estadd local Waves "Three"
	estadd local IFE "\checkmark"
	estadd local WFE "\checkmark"
	estadd local MuniFE "\checkmark"
	estadd local IC "\checkmark"
	estadd local CC "\checkmark"
	matrix N_g = e(N_g)
	local Individual = N_g[1,1]
	estadd local Individual `Individual'
	est store Model1e
	
	***Marginal effects for table****
	eststo m3: margins, dydx(indkomstplac20`dist') at(place_primsample=(0 1 2 3 4)) post
	
	*******WITH CONTROLVARIABLES AND GINI (adj.)
	xtreg redist indkomstplac20`dist' c.indkomstplac20`dist'#place_primsample giniadj_`dist' c.giniadj_`dist'#place_primsample  $ICOVAR  ${ccovar`dist'} i.municip if prim_sample==1, fe robust
	estadd local Waves "Three"
	estadd local IFE "\checkmark"
	estadd local WFE "\checkmark"
	estadd local MuniFE "\checkmark"
	estadd local IC "\checkmark"
	estadd local CC "\checkmark"
	matrix N_g = e(N_g)
	local Individual = N_g[1,1]
	estadd local Individual `Individual'
	est store Model1f
	
	***Marginal effects for table****
	eststo m4: margins, dydx(indkomstplac20`dist') at(place_primsample=(0 1 2 3 4)) post
	
	*******WITH CONTROLVARIABLES AND INCOME DIVERSITY
	xtreg redist indkomstplac20`dist' c.indkomstplac20`dist'#place_primsample incomediv_`dist' c.incomediv_`dist'#place_primsample  $ICOVAR  ${ccovar`dist'} i.municip if prim_sample==1, fe robust
	estadd local Waves "Three"
	estadd local IFE "\checkmark"
	estadd local WFE "\checkmark"
	estadd local MuniFE "\checkmark"
	estadd local IC "\checkmark"
	estadd local CC "\checkmark"
	matrix N_g = e(N_g)
	local Individual = N_g[1,1]
	estadd local Individual `Individual'
	est store Model1g
	
	***Marginal effects for table****
	eststo m5: margins, dydx(indkomstplac20`dist') at(place_primsample=(0 1 2 3 4)) post
	
}

	esttab Model1a Model1b Model1c Model1d Model1e Model1f Model1g using ".\inequalitypanel\results\panel_exposure_fulltable",lab nogap base wide tex star(+ 0.10 * 0.05 ** 0.01 *** 0.001) se b(%9.2f) /// 
		nomtitle replace nonotes drop(*muni* *wave*) nobaselevel ///
		refcat(1.place_primsample#c.indkomstplac20100 "Poor $\times$ Exposure to poor individuals" 1.place_primsample#c.indkomstplac80100 "Poor $\times$ Exposure to rich individuals" 1.place_primsample#c.giniadj_100 "Poor $\times$ Gini (adj.)" ///
		2.unemployed_RS "Working" 2.civilstand "Widowed" 1.samboende "Living alone") ///
		stats(IFE WFE MuniFE IC CC Waves r2 N Individual, ///
		labels("Individual FE" "Wave FE" "Municipality FE" "Individual Controls" "Contextual Controls" "Waves" "R-sqr(within)" "Observations" "Individuals") ///
		fmt(0 0 0 0 0 0 3 0 0)) ///
		mgroups("Model 0a" "Model 0b" "Model 0c" "Model 1" "Model 2" "Model 3" "Model 4",pattern(1 1 1 1 1 1 1) prefix(\multicolumn{@span}{c}{) suffix(}) span erepeat(\cmidrule(lr){@span})) 
		
		esttab Model1b Model1c Model1d Model1e Model1f using ".\inequalitypanel\results\panel_exposure",lab nogap base tex star(+ 0.10 * 0.05 ** 0.01 *** 0.001) se b(%9.2f) /// 
		nomtitle replace keep(*indkomstplac* *plac* *gini* ) nonotes nobaselevel ///
		refcat(1.place_primsample#c.indkomstplac20100 "Poor $\times$ Exposure to poor individuals" 1.place_primsample#c.indkomstplac80100 "Poor $\times$ Exposure to rich individuals" 1.place_primsample#c.giniadj_100 "Poor $\times$ Gini (adj.)") ///
		stats(IFE WFE MuniFE IC CC Waves r2 N Individual, ///
		labels("Individual FE" "Wave FE" "Municipality FE" "Individual Controls" "Contextual Controls" "Waves" "R-sqr(within)" "Observations" "Individuals") ///
		fmt(0 0 0 0 0 0 3 0 0)) ///
		mgroups("Model 0a" "Model 0b" "Model 0c" "Model 1" "Model 2" "Model 3",pattern(1 1 1 1 1 1) prefix(\multicolumn{@span}{c}{) suffix(}) span erepeat(\cmidrule(lr){@span})) 
		
esttab m1 m2 m3 m4 m5 using ".\inequalitypanel\results\panel_exposure_marginaleffects",replace lab nogap base tex nomtitle star(+ 0.10 * 0.05 ** 0.01 *** 0.001) se b(%9.2f) rename(1._at *Poor 2._at *Lower-Middle 3._at *Middle 4._at *Upper-Middle 5._at *Rich)
		
}

****************************************************************************
****************TABLE A10************************************************
********************************************************************************
if 1==1 {
	foreach dist in 100  {
	
	*******WITH CONTROLVARIABLES AND UNCONDITIONAL GINI
	xtreg redist giniadj_`dist' $ICOVAR  ${ccovar`dist'} i.municip if prim_sample==1, fe robust
	estadd local Waves "Three"
	estadd local IFE "\checkmark"
	estadd local WFE "\checkmark"
	estadd local MuniFE "\checkmark"
	estadd local IC "\checkmark"
	estadd local CC "\checkmark"
		matrix N_g = e(N_g)
	local Individual = N_g[1,1]
	estadd local Individual `Individual'
	est store Model1a
	
 	*******WITH CONTROLVARIABLES AND CONDITIONAL		
	xtreg redist giniadj_`dist' c.giniadj_`dist'#place_primsample  $ICOVAR  ${ccovar`dist'} i.municip if prim_sample==1, fe robust
	estadd local Waves "Three"
	estadd local IFE "\checkmark"
	estadd local WFE "\checkmark"
	estadd local MuniFE "\checkmark"
	estadd local IC "\checkmark"
	estadd local CC "\checkmark"
		matrix N_g = e(N_g)
	local Individual = N_g[1,1]
	estadd local Individual `Individual'
	est store Model1b
	
	***Marginal effects for table****
	eststo m1: margins, dydx(giniadj_`dist') at(place_primsample=(0 1 2 3 4)) post
	
	*******WITH CONTROLVARIABLES AND INCOME DIVERSITY
	xtreg redist incomediv_`dist' $ICOVAR  ${ccovar`dist'} i.municip if prim_sample==1, fe robust
	estadd local Waves "Three"
	estadd local IFE "\checkmark"
	estadd local WFE "\checkmark"
	estadd local MuniFE "\checkmark"
	estadd local IC "\checkmark"
	estadd local CC "\checkmark"
	matrix N_g = e(N_g)
	local Individual = N_g[1,1]
	estadd local Individual `Individual'
	est store Model1c

	*******WITH CONTROLVARIABLES AND UNCONDITIONAL INCOME DIVERSITY
	xtreg redist incomediv_`dist' c.incomediv_`dist'#place_primsample  $ICOVAR  ${ccovar`dist'} i.municip if prim_sample==1, fe robust
	estadd local Waves "Three"
	estadd local IFE "\checkmark"
	estadd local WFE "\checkmark"
	estadd local MuniFE "\checkmark"
	estadd local IC "\checkmark"
	estadd local CC "\checkmark"
	matrix N_g = e(N_g)
	local Individual = N_g[1,1]
	estadd local Individual `Individual'
	est store Model1d
	
	***Marginal effects for table****
	eststo m2: margins, dydx(incomediv_`dist') at(place_primsample=(0 1 2 3 4)) post
	
}

	esttab Model1a Model1b Model1c Model1d using ".\inequalitypanel\results\panel_gini_incomediversity_fulltable",lab nogap base wide tex star(+ 0.10 * 0.05 ** 0.01 *** 0.001) se b(%9.2f) /// 
		nomtitle replace nonotes drop(*muni* *wave*) order(*gini* *incomediv_*) nobaselevel ///
		refcat(1.place_primsample#c.giniadj_100 "Poor $\times$ Gini (adj.)" 1.place_primsample#c.incomediv_100 "Poor $\times$ Income diversity"  ///
		2.unemployed_RS "Working" 2.civilstand "Widowed" 1.samboende "Living alone") ///
		stats(IFE WFE MuniFE IC CC Waves r2 N Individual, ///
		labels("Individual FE" "Wave FE" "Municipality FE" "Individual Controls" "Contextual Controls" "Waves" "R-sqr(within)" "Observations" "Individuals") ///
		fmt(0 0 0 0 0 0 3 0 0)) ///
		mgroups("Model 1" "Model 2" "Model 3" "Model 4",pattern(1 1 1 1) prefix(\multicolumn{@span}{c}{) suffix(}) span erepeat(\cmidrule(lr){@span})) 
		

esttab m1 m2 using ".\inequalitypanel\results\panel_gini_incomediversity_marginaleffects",replace lab nogap base tex nomtitle star(+ 0.10 * 0.05 ** 0.01 *** 0.001) se b(%9.2f) rename(1._at *Poor 2._at *Lower-Middle 3._at *Middle 4._at *Upper-Middle 5._at *Rich)
		
}

	
****************************************************************************
**************** FIGURE 1: UPPER PANEL AND PANEL ESTIMATES FOR THE RICH (lower panel)***
********************************************************************************

if 1==1 {

frame copy panelanalysis temp,replace
cwf temp

    glo IV indkomstplac20
	glo IVlabel Exposure to Poor
	glo name eksponeringfattige
	glo name2 "Exposure to poor individuals"
	mat A = [.,.,.,.,.,.,.]
	loc i = 1

 
foreach dist of global afst {
	xtreg redist indkomstplac20`dist' c.indkomstplac20`dist'#place_primsample $ICOVAR ${ccovar`dist'} i.municip if prim_sample==1,  robust fe
	margins, dydx(indkomstplac20`dist') at(place_primsample=(4))
	mat b1 = r(table)[1,1]
	mat b2 = r(table)[5,1]
	mat b3 = r(table)[6,1]
	mat b4 = e(N)
	mat b5 = r(table)[4,1]
	loc ii = `i'-0.1
	mat b = `ii',1,b1,b2,b3,b4,b5
	mat A = A\b
	
	*drop INEQ
	
	loc ++i
}

***Marginal effects in 100 meter context

foreach dist in 100 {
	xtreg redist indkomstplac20`dist' c.indkomstplac20`dist'#place_primsample $ICOVAR ${ccovar`dist'} i.municip if prim_sample==1,  robust fe
	margins, dydx(indkomstplac20`dist') at(place_primsample=(0 1 2 3 4)) saving(".\inequalitypanel\results\marginsplot.dta", replace)
	
	frame create marginsplot
	cwf marginsplot
	
	use .\inequalitypanel\results\marginsplot.dta, clear
	
	twoway (rspike _ci_lb _ci_ub _at if _at!=5, sort pstyle(ci) lcolor("gray")) ///
		(rspike _ci_lb _ci_ub _at if _at==5, sort pstyle(ci) lcolor("black")) ///
		(scatter _margin _at if _at!=5,sort mc("gray") msymbol(o))  ///
		(scatter _margin _at if _at==5,sort mc("black") msymbol(o)) , ///
		 yline(0) yscale(range(-2 2))  ylabel(-2 -1 0 1 2) xlab(1 "Poor" 2 "Lower-Middle" 3 "Middle" 4 "Upper-Middle" 5 "Rich") xtitle("Income Group") ytitle("") title("Marginal Effect of Exposure to Poor Individuals across Income Groups (100 meters radius)",size(medsmall)) legend(off) name(figur`dist',replace)
	
	

}
cwf temp



}

******************************************************************************************
******CALCULATING SUBSTANTIAL EFEFCT + COMPARE EFFECT FROM DIFFERENT INCOME GROUPS
******************************************************************************************

foreach dist in 100 {
	
	***COMPARE EFFECTS
	xtreg redist ${IV}`dist' c.indkomstplac20`dist'#i.place_primsample $ICOVAR ${ccovar`dist'} i.municip if prim_sample==1,  robust fe
	margins, dydx(indkomstplac20`dist') at(place_primsample=(0 1 2 3 4)) pwcompare(effects)
	
	***SUBSTANTIAL EFFECT SIZE
	margins, dydx(indkomstplac20`dist') at(place_primsample=(4)) //calculating marginal effect for rich
	
	matrix B = r(b)	//saving in matrix
	mat rowname B =  Marginaleffect_Rich

	xtsum indkomstplac20100 if prim_sample==1 //calculating std. deviation for std. exposure
	
	matrix SD = r(sd_b) //saving in matrix
	mat rowname SD =  Std.Dev.ExposuretoPoor(AcrossWave)

	matrix effect = B*SD //multiplying SD with marginal effect
	mat rowname effect =  SubstantialEffect(beta*SD)
	
	****Compiling matrices
	mat saml = B 
	mat saml = saml \ SD

	mat saml = saml  \ effect

	
	putpdf begin
	putpdf table substantialeffect = matrix(saml), rownames
	
	putpdf save ".\inequalitypanel\results\substantialeffect", replace
	
	}

	
********************************************************************************
************ESTIMATING COEFFICIENTS FOR FIGURE A20******************
********************************************************************************
if 1==1 {
  
  	***adding gender, origin and ages as covariates in between-effect models
	egen gender_allwaves = max(koenRS),by(resppnr)
	egen origin_allwaves = max(oprindelse),by(resppnr)
	gen age_temp=alderRS if wave==2
	gen age_temp2=alderRS if wave==1
	egen age_allwaves = max(age_temp),by(resppnr)
	egen age_wave1 = max(age_temp2),by(resppnr)
	replace age_allwave=alderRS if wave==1
	replace age_allwave=alderRS if wave==2
	replace age_allwave=age_allwave+timesince if wave==3
	replace age_allwave=age_wave1+timesince if wave==3 & age_allwave==.

	
  loc i = 1
foreach dist of global afst {
	xtreg redist ${IV}`dist' c.indkomstplac20`dist'#place_primsample $ICOVAR ${ccovar`dist'} i.municip if prim_sample==1 & place_primsample==4,  robust fe
	margins, dydx(indkomstplac20`dist') at(place_primsample=(4))
	mat b1 = r(table)[1,1]
	mat b2 = r(table)[5,1]
	mat b3 = r(table)[6,1]
	mat b4 = e(N)
	mat b5 = r(table)[4,1]
	loc ii = `i'-0.1
	mat b = `ii',5,b1,b2,b3,b4,b5
	mat A = A\b
	
	*drop INEQ
	
	loc ++i
}

	loc i = 1
foreach dist of global afst {

	
	xtreg redist ${IV}`dist' c.indkomstplac20`dist'#place_primsample $ICOVAR ${ccovar`dist'} age_allwave origin_allwaves gender_allwaves i.municip if prim_sample==1 & place_primsample==4, be
	margins, dydx(indkomstplac20`dist') at(place_primsample=(4))
	mat b1 = r(table)[1,1]
	mat b2 = r(table)[5,1]
	mat b3 = r(table)[6,1]
	mat b4 = e(N)
	mat b5 = r(table)[4,1]
	loc ii = `i'+0.1
	mat b = `ii',6,b1,b2,b3,b4,b5
	mat A = A\b

	*drop INEQ
	
	loc ++i
}

}


********************************************************************************
****CROSS-SECTIONAL ESTIMATES (lower panel) FOR FIGURE 1 AND TABLE A9***********
*******************************************************************************
if 1==1 {
frame change cross_analysis
	
*******************************************************
********MAKING TABLE A9 FIRST*****************************
*******************************************************
if 1==1 {
	foreach dist in 100  {
	reg redist c.indkomstplac20`dist'##place if IF==1, robust
	estadd local TFE "$-$"
	estadd scalar ajr2 = e(r2_a)
	estadd local WFE "$-$"
	estadd local MuniFE "$-$"
	estadd local IC "$-$"
	estadd local CC "$-$"
	estadd scalar NSR 7
	est store Model1a
	
	***Marginal effects for table****
	eststo m1: margins, dydx(indkomstplac20`dist') at(place=(0 1 2 3 4)) post
	
	
 	*******WITH CONTROLVARIABLES
	areg redist c.indkomstplac20`dist'##place  $ICOVAR_cross  ${ccovar`dist'} if IF==1, absorb(municip) robust
	estadd local TFE "\checkmark"
	estadd scalar ajr2 = e(r2_a)
	estadd local MuniFE "\checkmark"
	estadd local IC "\checkmark"
	estadd local CC "\checkmark"
	estadd scalar NSR 7
	est store Model1b
	
	eststo m2: margins, dydx(indkomstplac20`dist') at(place=(0 1 2 3 4)) post

	
	 *******WITH CONTROLVARIABLES AND SHARE OF RICH
	areg redist c.indkomstplac20`dist'##place c.indkomstplac80`dist'##place $ICOVAR_cross  ${ccovar`dist'} if IF==1, absorb(municip) robust
	estadd local TFE "\checkmark"
	estadd scalar ajr2 = e(r2_a)
	estadd local MuniFE "\checkmark"
	estadd local IC "\checkmark"
	estadd local CC "\checkmark"
	estadd scalar NSR 7
	est store Model1c

	***Marginal effects for table****
	eststo m3: margins, dydx(indkomstplac20`dist') at(place=(0 1 2 3 4)) post
	
	
	*******WITH CONTROLVARIABLES AND GINI (adj.)
	areg redist c.indkomstplac20`dist'##place c.giniadj_`dist'##place  $ICOVAR_cross  ${ccovar`dist'} if IF==1, absorb(municip) robust
	estadd local TFE "\checkmark"
	estadd scalar ajr2 = e(r2_a)
	estadd local MuniFE "\checkmark"
	estadd local IC "\checkmark"
	estadd local CC "\checkmark"
	estadd scalar NSR 7
	est store Model1d
	
	***Marginal effects for table****
	eststo m4: margins, dydx(indkomstplac20`dist') at(place=(0 1 2 3 4)) post
	
}

		
	esttab Model1a Model1b Model1c Model1d using ".\inequalitypanel\results\cross_exposure_fulltable",lab nogap base wide tex nomtitle star(+ 0.10 * 0.05 ** 0.01 *** 0.001) se b(%9.2f) /// 
		nomtitle replace nonotes  nobaselevel drop(*survey*) ///
		refcat(1.place "Poor" 1.place#c.indkomstplac20100 "Poor $\times$ Exposure to poor individuals" 1.place#c.indkomstplac80100 "Poor $\times$ Exposure to rich individuals" 1.place#c.giniadj_100 "Poor $\times$ Gini (adj.)" ///
		1.koen "Female" 2.oprindelse "Danish origin" 2.unemployed_RS "Working" 2.civilstand "Widowed" 1.samboende "Living alone") ///
		stats(NSR TFE MuniFE IC CC ajr2 N, ///
		labels("Number of ESS-rounds" "Survey Round FE" "Municipality FE" "Individual controls" "Contextual controls" "Adjusted R^2" "N") ///
		fmt(0 0 0 0 0 3 0)) ///
		mgroups("Model 0" "Model 1" "Model 2" "Model 3",pattern(1 1 1 1) prefix(\multicolumn{@span}{c}{) suffix(}) span erepeat(\cmidrule(lr){@span})) 
		
	esttab m1 m2 m3 m4 using ".\inequalitypanel\results\panel_exposure_marginaleffects_cross",replace lab nogap base tex nomtitle star(+ 0.10 * 0.05 ** 0.01 *** 0.001) se b(%9.2f) rename(1._at *Poor 2._at *Lower-Middle 3._at *Middle 4._at *Upper-Middle 5._at *Rich)

		
}
	
	
*******************************************************
*****CROSS-SECTION ESTIMATES FOR THE RICH IN FIGURE 1*******	
*******************************************************
	frame copy cross_analysis temp_cross,replace
	cwf temp_cross  
	
	loc i = 1
	
foreach dist of global afst {
	areg redist c.indkomstplac20`dist' c.indkomstplac20`dist'#i.place i.place $ICOVAR_cross ${ccovar`dist'} if IF==1,  absorb(municip) robust
	margins, dydx(indkomstplac20`dist') at(place=(4))
	mat b1 = r(table)[1,1]
	mat b2 = r(table)[5,1]
	mat b3 = r(table)[6,1]
	mat b4 = e(N)
	mat b5 = r(table)[4,1]
	loc ii = `i'+0.1
	mat b = `ii',2,b1,b2,b3,b4,b5
	mat A = A\b
	
	*drop INEQ
	loc ++i
}

*****CROSS-SECTION RESULTS FOR THE RICH - INCLUDING POLITICAL IDEOLOGY*******	
	frame copy cross_analysis temp_cross,replace
	cwf temp_cross  
	
	loc i = 1
	
foreach dist of global afst {
	areg redist c.indkomstplac20`dist' c.indkomstplac20`dist'#i.place i.place $ICOVAR_cross_ideo ${ccovar`dist'} if IF==1,  absorb(municip) robust
	margins, dydx(indkomstplac20`dist') at(place=(4))
	mat b1 = r(table)[1,1]
	mat b2 = r(table)[5,1]
	mat b3 = r(table)[6,1]
	mat b4 = e(N)
	mat b5 = r(table)[4,1]
	loc ii = `i'+0.15
	mat b = `ii',7,b1,b2,b3,b4,b5
	mat A = A\b
	
	*drop INEQ
	loc ++i
}


}


********************************************************
*****ESTIMATING PANEL COEFFICIENTS FOR FIGURE A11************************
*******************************************************
if 1==1 {
	frame copy panelanalysis temp,replace
	cwf temp
	loc i = 1
	
foreach dist of global afst {
	xtreg redist indkomstplac20`dist' c.indkomstplac20`dist'#place_primsample $ICOVAR ${ccovar`dist'} i.municip if prim_sample==1 ,  robust fe
	margins, dydx(indkomstplac20`dist') at(place_primsample=(0))
	mat b1 = r(table)[1,1]
	mat b2 = r(table)[5,1]
	mat b3 = r(table)[6,1]
	mat b4 = e(N)
	mat b5 = r(table)[4,1]
	loc ii = `i'-0.1
	mat b = `ii',3,b1,b2,b3,b4,b5
	mat A = A\b
	
	*drop INEQ
	loc ++i
}


}

********************************************************
****ESTIMATING CROSS-SECTIONAL COEFFICIENTS FOR FIGURE A11************************
*******************************************************
if 1==1 {
	frame change cross_analysis
	frame copy cross_analysis temp_cross,replace
	cwf temp_cross    

	loc i = 1

foreach dist of global afst {
	areg redist indkomstplac20`dist' c.indkomstplac20`dist'#place i.place $ICOVAR_cross ${ccovar`dist'} if IF==1,  absorb(municip) robust
	margins, dydx(indkomstplac20`dist') at(place=(0))
	mat b1 = r(table)[1,1]
	mat b2 = r(table)[5,1]
	mat b3 = r(table)[6,1]
	mat b4 = e(N)
	mat b5 = r(table)[4,1]
	loc ii = `i'+0.1
	mat b = `ii',4,b1,b2,b3,b4,b5
	mat A = A\b
	
	*drop INEQ
	loc ++i
}

}


clear 
svmat A

drop in 1

************************************************************************
************MAKING FIGURE 1 (PRIMARY FIGURE)**************************
************************************************************************
tw (scatter A3 A1 if A2==1 , mc(black) ms(o))  ///
	(rspike A4 A5 A1 if A2==1 ,lc(black)) ///
	(scatter A3 A1 if A2==2, mc(gs12) ms(o)) (rspike A4 A5 A1 if A2==2,lc(gs12)) ///
	, xscal(range(0.7 9.3) extend) xlab(1 "100" 2 "150" 3 "200" 4 "250" 5 "500" 6 "1000" 7 "1500" 8 "2000" 9 "2500") ///
	ytit("") ysca(extend)  yline(0) name(FE_EXPOSURETOPOOR_compare,replace) legend(position(7) ring(0) label(1 "Panel Estimate") label(3 "Cross-Section Estimate") order(1 3)) xtit("Size of Context (radius in meters)") title("Marginal Effects of Exposure to Poor Individuals for the Rich across Context Sizes",size(medsmall))

gr combine figur100 FE_EXPOSURETOPOOR_compare, col(1) ysize(10) graphregion(margin(zero) color(white))

gr export ".\inequalitypanel\results\primaryillustra.pdf",replace

************************************************************************
*******************MAKING FIGURE A11**********************************
************************************************************************
tw (scatter A3 A1 if A2==3 , mc(black) ms(o)) (rspike A4 A5 A1 if A2==3 ,lc(black))  ///
	(scatter A3 A1 if A2==4, mc(gs12) ms(o)) (rspike A4 A5 A1 if A2==4 ,lc(gs12)) ///
	, xscal(range(0.7 9.3) extend) xlab(1 "100" 2 "150" 3 "200" 4 "250" 5 "500" 6 "1000" 7 "1500" 8 "2000" 9 "2500" ) ///
	ytit("") ysca(extend)  yline(0) name(FE_EXPOSURETOPOOR_comparePoor,replace) legend(position(11) ring(0) label(1 "Panel Estimate") label(3 "Cross-Section Estimate") order(1 3)) xtit("Size of Context (radius in meters)")
	gr combine  FE_EXPOSURETOPOOR_comparePoor, col(1) graphregion(margin(zero) color(white))
	
gr export ".\inequalitypanel\results\poorcomparision.pdf",replace

************************************************************************
***************MAKING FIGURE A20************************
************************************************************************

tw (scatter A3 A1 if A2==5 , mc(black) ms(o))  ///
	(rspike A4 A5 A1 if A2==5,lc(black)) ///
	(scatter A3 A1 if A2==6 , mc(gs12) ms(o))  ///
	(rspike A4 A5 A1 if A2==6,lc(gs12)) ///
	, xscal(range(0.7 9.3) extend) xlab(1 "100" 2 "150" 3 "200" 4 "250" 5 "500" 6 "1000" 7 "1500" 8 "2000" 9 "2500") ///
	ytit("") ysca(extend)  yline(0) name(FE_EXPOSURETOPOOR_RICHREST,replace) legend(position(11) ring(0) ///
	label(1 "Within-Individual Estimate") label(3 "Between-Individual Estimate") order(1 3)) xtit("Size of Context (radius in meters)") title("")

gr combine FE_EXPOSURETOPOOR_RICHREST, col(1) graphregion(margin(zero) color(white))

gr export ".\inequalitypanel\results\restrict_to_rich.pdf",replace

************************************************************************
************MAKING FIGURE A24*****************************************
************************************************************************

tw (scatter A3 A1 if A2==1 , mc(black) ms(o))  ///
	(rspike A4 A5 A1 if A2==1 ,lc(black)) ///
	(scatter A3 A1 if A2==2, mc(gs12) ms(o)) ///
	(rspike A4 A5 A1 if A2==2,lc(gs12)) ///
	(scatter A3 A1 if A2==7, mc(gs14) ms(o)) ///
	(rspike A4 A5 A1 if A2==7,lc(gs14)) ///
	, xscal(range(0.7 9.3) extend) xlab(1 "100" 2 "150" 3 "200" 4 "250" 5 "500" 6 "1000" 7 "1500" 8 "2000" 9 "2500") ///
	ytit("") ysca(extend)  yline(0) name(FE_EXPOSURETOPOOR_compare_ideo,replace) legend(position(7) ring(0) label(1 "Panel Estimate") label(3 "Cross-Section Estimate") label(5 "Cross-Section Estimate adding Pol. Ideology") order(1 3 5)) xtit("Size of Context (radius in meters)") title("Marginal Effects of Exposure to Poor Individuals for the Rich across Context Sizes",size(medsmall))

gr combine FE_EXPOSURETOPOOR_compare_ideo, col(1)  graphregion(margin(zero) color(white))

gr export ".\inequalitypanel\results\primaryillustra_compareideology.pdf",replace

 capture log close //closing log-files

 
****************************************************************************
****************ROBUSTNESS CHECKS************************************************
********************************************************************************
****************SECTION D.1************************************************
********************************************************************************
if 1==1 {

frame change panelanalysis
frame copy panelanalysis temp,replace
cwf temp

***control variables
recode unemployed_R (1=1) (else=0), gen(iarbejde)
recode unemployed_R (2=1) (else=0), gen(arbejdslos)
recode unemployed_R (3=1) (else=0), gen(pensionist)
recode unemployed_R (4=1) (else=0), gen(fortidspensionist)
recode unemployed_R (5=1) (else=0), gen(studerende)

lab var iarbejde "Employed"
lab var arbejdslos "Unemployed"
lab var pensionist "Retired"
lab var fortidspensionist "Early Retirement"
lab var studerende "Student"

lab var redist "Governtment should reduce differences in income levels"

recode place_primsample (4=1) (else=0), gen(rich)
recode place_primsample (3=1) (else=0), gen(upper_middle)
recode place_primsample (2=1) (else=0), gen(middle)
recode place_primsample (1=1) (else=0), gen(lower_middle)
recode place_primsample (1=0) (else=0), gen(poor)

lab var rich "Rich"
lab var upper_middle "Upper-Middle"
lab var middle "Middle"
lab var lower_middle "Lower-Middle"
lab var poor "Poor"

gen RedistributionAttitudes = redist
gen Male = koenRS
gen Age = alderRS
gen HouseholdIncome = hhi_ln
gen YearsOfEducation =EduYearsRS
gen UnemploymentContext = unempl_narrow_100
gen MedianIncomeContext = medianinc_100
gen NeighborsContext = neigh_100
gen EthicDiversityContext = ethdiv_100
gen Rich = rich
gen UpperMiddle = upper_middle
gen Middle = middle
gen LowerMiddle = lower_middle

***panel respondents in first wave they participated in the panel
gen panel=.
replace panel=1 if wave==1

egen panel_temp=total(wave),by(resppnr)
replace panel=1 if panel_temp==5 & wave==2
gen wave_new = wave if panel_temp==4

foreach dist of global afst  {
	xtset id wave
	***CREATING CHANGES VARIABLE OF EXPOSURE TO POOR FOR SAMPLE WITH ONLY ROUND4 RESPONDENTS 
gen delta_indkomstplac20`dist' = d.indkomstplac20`dist' 
egen mean_delta`dist' = mean(delta_indkomstplac20`dist'),by(resppnr)

****making mean deviation for those five resp. who are only in wave 1 and wave 3
	xtset id wave_new ,delta(2)

***CREATING CHANGES VARIABLE OF EXPOSURE TO POOR FOR SAMPLE WITH ONLY ROUND4 RESPONDENTS 
gen delta_indkomstplac20new`dist' = d.indkomstplac20`dist' 
egen mean_deltatemp`dist' = mean(delta_indkomstplac20new`dist'),by(resppnr)

replace mean_delta`dist'=mean_deltatemp`dist'  if mean_delta`dist'==.

xtset id wave
}

***INVERSE PROBABILITY WEIGHTING 

foreach dist of global afst  {

sum mean_delta`dist' if prim_sample==1,de
***CREATING DUMMYVARIABLE, WHERE 0 INDICATES THOSE WITH NEGATIVE CHANGES IN EXPOSURE TO POOR  AND 1 INDICATES THOSE WITH POSITIVE CHANGES IN  EXPOSURE TO POOR 
gen dummy_exposure`dist' = 0 if  mean_delta`dist'< 0     & mean_delta`dist'!=. & prim_sample==1 & panel==1
replace dummy_exposure`dist' = 1 if  mean_delta`dist'> 0 & mean_delta`dist'!=. & prim_sample==1 & panel==1
replace dummy_exposure`dist' =. if prim_sample!=1 
	
logit dummy_exposure`dist' redist koenRS alderRS hhi_ln EduYearsRS unempl_narrow_`dist' medianinc_`dist' neigh_`dist' ethdiv_`dist' rich upper_middle middle lower_middle if prim_sample==1 & panel==1
predict ps`dist' if prim_sample==1 & panel==1  //Inverse-probability weights are stored in a variable called ps - first getting propensity score
replace ps`dist'=1/ps`dist' if dummy_exposure`dist'==1 & prim_sample==1 & panel==1 //for subjects who recived high-exposure to poor,, the weight is equal to the reciprocal of the predicted probability of treatment 
replace ps`dist'=1/(1-ps`dist') if dummy_exposure`dist'==0 & prim_sample==1 & panel==1  //for subjects, who received low-exposure to poor, the weight is equality to the reciprocal of the predicted probability of not receiving a high-exposure to poor; the probability of not receiving high-exposure is just one minus the probability of high-exposure
egen max_ps`dist' = max(ps`dist'),by(resppnr)
}




****************************************************************************
****************TABLE A13************************************************
********************************************************************************
if 1==1 {
	foreach dist in 100  {
		***normal
	xtreg redist indkomstplac20`dist' c.indkomstplac20`dist'#place_primsample  $ICOVAR  ${ccovar`dist'} i.municip if prim_sample==1, fe robust
	estadd local Waves "Three"
	estadd local IFE "\checkmark"
	estadd local WFE "\checkmark"
	estadd local MuniFE "\checkmark"
	estadd local IC "\checkmark"
	estadd local CC "\checkmark"
	matrix N_g = e(N_g)
	local Individual = N_g[1,1]
	estadd local Individual `Individual'
	est store Model1a
	
	eststo m_normal: margins, dydx(indkomstplac20100) at(place_primsample=(0 1 2 3 4)) post

	
 	*******INVERSE PROBABILITY WEIGTHING
	xtreg redist indkomstplac20`dist' c.indkomstplac20`dist'#place_primsample  $ICOVAR  ${ccovar`dist'} i.municip if prim_sample==1 [pw= max_ps`dist'], fe robust
	estadd local Waves "Three"
	estadd local IFE "\checkmark"
	estadd local WFE "\checkmark"
	estadd local MuniFE "\checkmark"
	estadd local IC "\checkmark"
	estadd local CC "\checkmark"
	matrix N_g = e(N_g)
	local Individual = N_g[1,1]
	estadd local Individual `Individual'
	est store Model1b
	
	eststo m_doublerobust: margins, dydx(indkomstplac20100) at(place_primsample=(0 1 2 3 4)) post

	
}

	esttab Model1a Model1b using ".\inequalitypanel\results\panel_exposure_doublerobust",lab nogap base wide tex star(+ 0.10 * 0.05 ** 0.01 *** 0.001) se b(%9.2f) /// 
		nomtitle replace nonotes drop(*muni* *wave*) nobaselevel ///
		refcat(1.place_primsample#c.indkomstplac20100 "Poor $\times$ Exposure to poor individuals" 1.place_primsample#c.indkomstplac80100 "Poor $\times$ Exposure to rich individuals" 1.place_primsample#c.giniadj_100 "Poor $\times$ Gini (adj.)" ///
		2.unemployed_RS "Working" 2.civilstand "Widowed" 1.samboende "Living alone") ///
		stats(IFE WFE MuniFE IC CC Waves r2 N Individual, ///
		labels("Individual FE" "Wave FE" "Municipality FE" "Individual Controls" "Contextual Controls" "Waves" "R-sqr(within)" "Observations" "Individuals") ///
		fmt(0 0 0 0 0 0 3 0 0)) ///
		mgroups("Basic TWFE" "Double-Robust TWFE" ,pattern(1 1) prefix(\multicolumn{@span}{c}{) suffix(}) span erepeat(\cmidrule(lr){@span})) 
		
	esttab m_normal m_doublerobust using ".\inequalitypanel\results\panel_exposure_doublerobustmarginaleffects",replace lab nogap base tex nomtitle star(+ 0.10 * 0.05 ** 0.01 *** 0.001) se b(%9.2f) rename(1._at *Poor 2._at *Lower-Middle 3._at *Middle 4._at *Upper-Middle 5._at *Rich)

}
	
********************************************************************************
******************************TABLE A12****************************************
********************************************************************************
if 1==1 {
	frame copy temp describweight,replace
	cwf describweight
	
	keep if prim_sample==1 & panel==1 
	
	global DESCVAR redist koenRS alderRS hhi_ln EduYearsRS unempl_narrow_100 medianinc_100 neigh_100 ethdiv_100 rich upper_middle middle lower_middle
	
	local count: word count $DESCVAR
	mat diststat = J(`count',4,.)
	
	local i =1
foreach dist in $DESCVAR{
sum `dist' [iw=ps100] if dummy_exposure100==0
mat diststat[`i',1] = r(N)
mat diststat[`i',2] = r(mean)
sum `dist' [iw=ps100] if dummy_exposure100==1
mat diststat[`i',3] = r(N)
mat diststat[`i',4] = r(mean)
local i = `i'+1
	}

	mat colname diststat = Observations(NegativeExposure) Mean(NegativeExposure) Observations(PositiveExposure) Mean(PositiveExposure)
	mat rowname diststat = redist koenRS alderRS hhi_ln EduYearsRS unempl_narrow_100 medianinc_100 neigh_100 ethdiv_100 rich upper_middle middle lower_middle
*genere output
frmttable using ".\inequalitypanel\results\balance_afterweight.tex", statmat(diststat) varlabels tex replace  sfmt(g,f,g,f,g,f) fragment 

********************************************************************************
******************************TABLE A11****************************************
********************************************************************************

global DESCVAR redist koenRS alderRS hhi_ln EduYearsRS unempl_narrow_100 medianinc_100 neigh_100 ethdiv_100 rich upper_middle middle lower_middle
	
		local count: word count $DESCVAR
	mat diststat = J(`count',4,.)
	
	local i =1
foreach dist in $DESCVAR{
sum `dist'  if dummy_exposure100==0
mat diststat[`i',1] = r(N)
mat diststat[`i',2] = r(mean)
sum `dist'  if dummy_exposure100==1
mat diststat[`i',3] = r(N)
mat diststat[`i',4] = r(mean)
local i = `i'+1
	}

	mat colname diststat = Observations(NegativeExposure) Mean(NegativeExposure) Observations(PositiveExposure) Mean(PositiveExposure)
	mat rowname diststat = redist koenRS alderRS hhi_ln EduYearsRS unempl_narrow_100 medianinc_100 neigh_100 ethdiv_100 rich upper_middle middle lower_middle
*genere output
frmttable using ".\inequalitypanel\results\balance_beforeweight.tex", statmat(diststat) varlabels tex replace  sfmt(g,f,g,f,g,f) fragment 

}
	

********************************************************************************
******************************FIGURE A12****************************************
********************************************************************************
	
if 1==1 {
	cwf temp
	  glo IV indkomstplac80
	glo IVlabel Exposure to Rich
	glo name eksponeringrige
	glo name2 "Exposure to Rich"
	mat A = [.,.,.,.,.,.]
loc i = 1
foreach dist of global afst {
	
	****FULL SAMPLE
	xtreg redist indkomstplac20`dist' c.indkomstplac20`dist'#place_primsample  $ICOVAR  ${ccovar`dist'} i.municip if prim_sample==1, fe robust
	margins, dydx(indkomstplac20`dist') at(place_primsample=(4))
	mat b1 = r(table)[1,1]
	mat b2 = r(table)[5,1]
	mat b3 = r(table)[6,1]
	mat b4 = e(N)
	loc ii = `i'-0.1
	mat b = `ii',1,b1,b2,b3,b4
	mat A = A\b

	****WITH WEIGHTS
	xtreg redist indkomstplac20`dist' c.indkomstplac20`dist'#place_primsample  $ICOVAR  ${ccovar`dist'} i.municip if prim_sample==1 [pw= max_ps`dist'], fe robust
	margins, dydx(indkomstplac20`dist') at(place_primsample=(4))
	mat b1 = r(table)[1,1]
	mat b2 = r(table)[5,1]
	mat b3 = r(table)[6,1]
	mat b4 = e(N)
	loc ii = `i'+0.2
	mat b = `ii',2,b1,b2,b3,b4
	mat A = A\b
	
	
	loc ++i

	}
	
	clear 
svmat A

drop in 1

tw (scatter A3 A1 if A2==1, mc(black) ms(o)) (rspike A4 A5 A1 if A2==1,lc(black))  ///
	(scatter A3 A1 if A2==2, mc(gs12) ms(o)) (rspike A4 A5 A1 if A2==2, lc(gs12)) ///
	, xscal(range(0.7 9.3) extend) xlab(1 "100" 2 "150" 3 "200" 4 "250" 5 "500" 6 "1000" 7 "1500" 8 "2000" 9 "2500" ) ///
	ytit("") ysca(extend) yline(0) name(DOBBELT_ROBUST_TWFE,replace) legend(position(11) ring(0)  label(1 "Standard TWFE")  label(3 "Double-Robust TWFE") order(1 3)) xtit("Size of Context (radius in meters)") tit("Marginal Effect of Exposure to Poor Individuals for the Rich")
	
	

	gr combine  DOBBELT_ROBUST_TWFE, col(1) graphregion(margin(zero) color(white))
	gr export ".\inequalitypanel\results\DOBBELT_ROBUST_TWFE.pdf",replace

}

********************************************************************************
******************************FIGURE A13****************************************
********************************************************************************
frame change panelanalysis
frame copy panelanalysis temp,replace
cwf temp


if 1==1 {
glo name2 "Exposure to Poor"
	mat A = [.,.,.,.,.,.]
	loc i = 1
	
foreach dist of global afst {
	*Normal TWFE
	xtreg redist indkomstplac20`dist' c.indkomstplac20`dist'#i.place_primsample $ICOVAR ${ccovar`dist'} i.municip if prim_sample==1 , fe robust //PERFORMING NORMALTWFE
	margins, dydx(indkomstplac20`dist') at(place_primsample=(4))

	mat b1 = r(table)[1,1]
	mat b2 = r(table)[5,1]
	mat b3 = r(table)[6,1]
	mat b4 = e(N)
	loc ii = `i'
	mat b = `ii',1,b1,b2,b3,b4
	mat A = A\b
	
	************************************************************************
	************TREATMENT EFFECT IN PERIOD 1************************
	************************************************************************

	xtreg redist indkomstplac20`dist' c.indkomstplac20`dist'#i.place_primsample $ICOVAR ${ccovar`dist'} i.municip if prim_sample==1 & wave!=3, fe robust //PERFORMING NORMALTWFE
	margins, dydx(indkomstplac20`dist') at(place_primsample=(4))

	mat b1 = r(table)[1,1]
	mat b2 = r(table)[5,1]
	mat b3 = r(table)[6,1]
	mat b4 = e(N)
	loc ii = `i'-0.1
	mat b = `ii',2,b1,b2,b3,b4
	mat A = A\b
	

	************************************************************************
	************TREATMENT EFFECT IN PERIOD 2************************
	************************************************************************

	xtreg redist indkomstplac20`dist' c.indkomstplac20`dist'#i.place_primsample $ICOVAR ${ccovar`dist'} i.municip if prim_sample==1 & wave!=1, fe robust //PERFORMING NORMALTWFE
	margins, dydx(indkomstplac20`dist') at(place_primsample=(4))

	mat b1 = r(table)[1,1]
	mat b2 = r(table)[5,1]
	mat b3 = r(table)[6,1]
	mat b4 = e(N)
	loc ii = `i'+0.1
	mat b = `ii',3,b1,b2,b3,b4
	mat A = A\b
	
	loc ++i

}

clear 
	svmat A

	drop in 1

	tw (scatter A3 A1 if A2==1, mc(black) ms(o)) (rspike A4 A5 A1 if A2==1 ,lc(black)) ///
	 (scatter A3 A1 if A2==2, mc(gs8) ms(o)) (rspike A4 A5 A1 if A2==2 ,lc(gs8)) ///
	 (scatter A3 A1 if A2==3, mc(gs13) ms(o)) (rspike A4 A5 A1 if A2==3 ,lc(gs13)) ///
	, xscal(range(0.7 9.3) extend) xlab(1 "100" 2 "150" 3 "200" 4 "250" 5 "500" 6 "1000" 7 "1500" 8 "2000" 9 "2500" ) ///
	ytit("") ysca(extend) yline(0) name(TWFE_STAGGERED,replace) legend(position(11) ring(0)  label(1 "Standard TWFE")  label(3 "TWFE Period 1") label(5 "TWFE Period 2")  order(1 3 5)) xtit("Size of Context (radius in meters)") tit("Marginal Effect of Exposure to Poor Individuals for the Rich")


	
	gr combine  TWFE_STAGGERED, col(1) graphregion(margin(zero) color(white))
	gr export ".\inequalitypanel\results\TWFE_STAGGERED.pdf",replace

}
}


********************************************************************************
****************SECTION D.2************************************************
****************************************************************************
****************TABLE A14 AND FIGURE A14************************************************
********************************************************************************
if 1==1 {

frame change panelanalysis
global afstande 100 150 250 500 2500
	
	foreach dist of global afstande {

	***CONTEXT VARIABLE
	gen POOR = exposure_weigthed`dist'

	gen enligfors = enligfors_`dist'
	gen agecon = agespread_`dist'
	gen unemp =unempl_narrow_`dist'
	gen median = medianinc_`dist'
	gen ethdiv = ethdiv_`dist'
	gen turnover = residentialturnover_`dist'
	gen neigh = neigh_`dist'
	global CCOVAR  agecon unemp median ethdiv turnover neigh enligfors

 	*******WITH CONTROLVARIABLES
	xtreg redist POOR c.POOR#place_primsample  $ICOVAR  $CCOVAR i.municip if prim_sample==1, fe robust
	estadd local IFE "\checkmark"
	estadd local WFE "\checkmark"
	estadd local MuniFE "\checkmark"
	matrix N_g = e(N_g)
	local Individual = N_g[1,1]
	estadd local Individual `Individual'
	est store Model`dist'
	
	***Marginal effects for table****
	eststo m`dist': margins, dydx(POOR) at(place_primsample=(0 1 2 3 4)) post
	
	drop POOR
	drop agecon unemp median ethdiv turnover neigh enligfors
}
	***CONTEXT VARIABLE LABELS
	gen POOR = 0
	lab var POOR "Exposure to poor individuals (gradual)"

	gen agecon = 0
	lab var agecon "Age variation"

	gen enligfors =0 
	lab var enligfors "Share single-parent HH"
	
	gen unemp =0 
	lab var unemp "Share of unemployed"

	gen median = 0
	lab var median "Median income"


	gen ethdiv = 0
	lab var ethdiv "Ethnic diversity"

	gen turnover = 0
	lab var turnover "Residents' mobility"

	gen neigh = 0
	lab var neigh "Population density"
	
esttab Model100 Model150 Model250 Model500 Model2500 using ".\inequalitypanel\results\panel_exposure_flexexpos",lab nogap base tex nomtitle star(+ 0.10 * 0.05 ** 0.01 *** 0.001) se b(%9.2f) /// 
		nomtitle replace nonotes drop(*munic* *wave*) nobaselevel ///
			refcat(1.place_primsample#c.POOR "Poor $\times$ Exposure to poor individuals" ///
		2.unemployed_RS "Working" 2.civilstand "Widowed" 1.samboende "Living alone") ///
		stats(IFE WFE MuniFE r2 N Individual, ///
		labels("Individual FE" "Wave FE" "Municipality FE" "R-sqr(within)" "Observations" "Individuals") ///
		fmt(0 0 0 3 0 0)) ///
		mgroups("100 meter" "150 meter" "250 meter" "500 meter" "2500 meter",pattern(1 1 1 1 1) prefix(\multicolumn{@span}{c}{) suffix(}) span erepeat(\cmidrule(lr){@span})) 
		
	esttab m100 m150 m250 m500 m2500 using ".\inequalitypanel\results\panel_exposure_flexexposmarginaleffects",replace lab nogap base tex nomtitle star(+ 0.10 * 0.05 ** 0.01 *** 0.001) se b(%9.2f) rename(1._at *Poor 2._at *Lower-Middle 3._at *Middle 4._at *Upper-Middle 5._at *Rich)

		drop agecon unemp median ethdiv turnover neigh POOR enligfors //deleting labs

******MARGINAL EFFECTS
frame copy panelanalysis temp,replace
cwf temp

if 1==1 {
    glo IV exposure_weigthed
	glo IVlabel Exposure to poor individuals (gradual)
	glo name eksponeringfattige
	glo name2 "Exposure to poor individuals (gradual)"
	mat A = [.,.,.,.,.,.,.]
loc i = 1

  
foreach dist of global afst {

	***FULL
	xtreg redist exposure_weigthed`dist' c.exposure_weigthed`dist'#place_primsample $ICOVAR ${ccovar`dist'} i.municip if prim_sample==1, robust fe
	margins, dydx(exposure_weigthed`dist') at(place_primsample=(4))
	mat b1 = r(table)[1,1]
	mat b2 = r(table)[5,1]
	mat b3 = r(table)[6,1]
	mat b4 = e(N)
	mat b5 = r(table)[4,1]
	loc ii = `i'
	mat b = `ii',1,b1,b2,b3,b4,b5
	mat A = A\b
	
	
	
	loc ++i
}

clear 
svmat A

drop in 1


tw (scatter A3 A1 if A2==1, mc(black) ms(o)) (rspike A4 A5 A1 if A2==1,lc(black)) ///
	, xscal(range(0.7 9.3) extend) xlab(1 "100" 2 "150" 3 "200" 4 "250" 5 "500" 6 "1000" 7 "1500" 8 "2000" 9 "2500" ) ///
	ytit("") ysca(extend)  yline(0) name(FE_EXPOSURETOPOOR_FLEXIBLE,replace) xtit("Size of Context (radius in meters)") legend(off)
		gr combine  FE_EXPOSURETOPOOR_FLEXIBLE, col(1)  graphregion(margin(zero) color(white))
	gr export ".\inequalitypanel\results\illustration_flexexposure.pdf",replace


}

		
		
}
		
****************************************************************************
****************TABLE A15 AND FIGURE A15************************************************
********************************************************************************

if 1==1 {
	frame change panelanalysis

	foreach dist of global afstande {

	***CONTEXT VARIABLE
	gen POOR = halfofmedian`dist'
	gen enligfors = enligfors_`dist'

	gen agecon = agespread_`dist'
	gen unemp =unempl_narrow_`dist'
	gen median = medianinc_`dist'
	gen ethdiv = ethdiv_`dist'
	gen turnover = residentialturnover_`dist'
	gen neigh = neigh_`dist'
	global CCOVAR  agecon unemp median ethdiv turnover neigh enligfors

 	*******WITH CONTROLVARIABLES
	xtreg redist POOR c.POOR#place_primsample  $ICOVAR  $CCOVAR i.municip if prim_sample==1, fe robust
	estadd local IFE "\checkmark"
	estadd local WFE "\checkmark"
	estadd local MuniFE "\checkmark"
	matrix N_g = e(N_g)
	local Individual = N_g[1,1]
	estadd local Individual `Individual'
	est store Model`dist'
	
	***Marginal effects for table****
	eststo m`dist': margins, dydx(POOR) at(place_primsample=(0 1 2 3 4)) post
	
	drop POOR
	drop agecon unemp median ethdiv turnover neigh enligfors
}
	***CONTEXT VARIABLE LABELS
	gen POOR = 0
	lab var POOR "Exposure to poor individuals (half of median)"

	gen agecon = 0
	lab var agecon "Age variation"

	gen unemp =0 
	lab var unemp "Share of unemployed"

	gen median = 0
	lab var median "Median income"
	
	gen enligfors =0 
	lab var enligfors "Share single-parent HH"

	gen ethdiv = 0
	lab var ethdiv "Ethnic diversity"

	gen turnover = 0
	lab var turnover "Residents' mobility"

	gen neigh = 0
	lab var neigh "Population density"
	
esttab Model100 Model150 Model250 Model500 Model2500 using ".\inequalitypanel\results\panel_exposure_halfofmedian",lab nogap base tex nomtitle star(+ 0.10 * 0.05 ** 0.01 *** 0.001) se b(%9.2f) /// 
		nomtitle replace nonotes drop(*munic* *wave*) nobaselevel ///
			refcat(1.place_primsample#c.POOR "Poor $\times$ Exposure to poor individuals" ///
		2.unemployed_RS "Working" 2.civilstand "Widowed" 1.samboende "Living alone") ///
		stats(IFE WFE MuniFE r2 N Individual, ///
		labels("Individual FE" "Wave FE" "Municipality FE" "R-sqr(within)" "Observations" "Individuals") ///
		fmt(0 0 0 3 0 0)) ///
		mgroups("100 meter" "150 meter" "250 meter" "500 meter" "2500 meter",pattern(1 1 1 1 1) prefix(\multicolumn{@span}{c}{) suffix(}) span erepeat(\cmidrule(lr){@span})) 

esttab m100 m150 m250 m500 m2500 using ".\inequalitypanel\results\panel_exposure_halfofmedianmarginaleffects",replace lab nogap base tex nomtitle star(+ 0.10 * 0.05 ** 0.01 *** 0.001) se b(%9.2f) rename(1._at *Poor 2._at *Lower-Middle 3._at *Middle 4._at *Upper-Middle 5._at *Rich)

		
		drop agecon unemp median ethdiv turnover neigh POOR enligfors //deleting labs
		
******MARGINAL EFFECTS
		frame copy panelanalysis temp,replace
		cwf temp

if 1==1 {
    glo IV halfofmedian
	glo IVlabel Exposure to poor individuals (half of median)
	glo name eksponeringfattige
	glo name2 "Exposure to poor individuals (half of median)"
	mat A = [.,.,.,.,.,.,.]
	loc i = 1

  
foreach dist of global afst {
	
	***MAIN MODEL
	xtreg redist halfofmedian`dist' c.halfofmedian`dist'#place_primsample $ICOVAR ${ccovar`dist'} i.municip if prim_sample==1,  robust fe
	margins, dydx(halfofmedian`dist') at(place_primsample=(4))
	mat b1 = r(table)[1,1]
	mat b2 = r(table)[5,1]
	mat b3 = r(table)[6,1]
	mat b4 = e(N)
	mat b5 = r(table)[4,1]
	loc ii = `i'
	mat b = `ii',1,b1,b2,b3,b4,b5
	mat A = A\b
	

	loc ++i
}


clear 
svmat A

drop in 1

tw (scatter A3 A1 if A2==1, mc(black) ms(o)) (rspike A4 A5 A1 if A2==1,lc(black)) ///
	, xscal(range(0.7 9.3) extend) xlab(1 "100" 2 "150" 3 "200" 4 "250" 5 "500" 6 "1000" 7 "1500" 8 "2000" 9 "2500" ) ///
	ytit("") ysca(extend)  yline(0) name(FE_EXPOSURETOPOOR_HALFOFMEDian,replace) xtit("Size of Context (radius in meters)") legend(off)
	gr combine  FE_EXPOSURETOPOOR_HALFOFMEDian, col(1) graphregion(margin(zero) color(white))
	gr export ".\inequalitypanel\results\illustration_halfofmedian.pdf",replace

}

		
		
}
	

********************************************************************************
****************SECTION D.3************************************************
****************************************************************************
****************************************************************************
****************MAKING TABLE A16 and FIGURE A16************************************************
********************************************************************************
if 1==1 {
	frame change fullpanel
	global afstande 100 150 250 500 2500
	foreach dist of global afstande {

	***CONTEXT VARIABLE
	gen POOR = indkomstplac20`dist'

	gen enligfors = enligfors_`dist'
	gen agecon = agespread_`dist'
	gen unemp =unempl_narrow_`dist'
	gen median = medianinc_`dist'
	gen ethdiv = ethdiv_`dist'
	gen turnover = residentialturnover_`dist'
	gen neigh = neigh_`dist'
	global CCOVAR  agecon unemp median ethdiv turnover neigh enligfors

 	*******WITH CONTROLVARIABLES
	xtreg redist POOR c.POOR#place_fullsample  $ICOVAR  $CCOVAR i.municip, fe robust
	estadd local IFE "\checkmark"
	estadd local MuniFE "\checkmark"
	estadd local WFE "\checkmark"
	matrix N_g = e(N_g)
	local Individual = N_g[1,1]
	estadd local Individual `Individual'
	est store Model`dist'
	
	***Marginal effects for table****
	eststo m`dist': margins, dydx(POOR) at(place_fullsample=(0 1 2 3 4)) post
	
	drop POOR
	drop agecon unemp median ethdiv turnover neigh enligfors
}
	
	***CONTEXT VARIABLE LABELS
	gen POOR = 0
	lab var POOR "Exposure to poor individuals"

	gen agecon = 0
	lab var agecon "Age variation"

	gen unemp =0 
	lab var unemp "Share of unemployed"

	gen median = 0
	lab var median "Median income"

	gen enligfors =0 
	lab var enligfors "Share single-parent HH"

	gen ethdiv = 0
	lab var ethdiv "Ethnic diversity"

	gen turnover = 0
	lab var turnover "Residents' mobility"

	gen neigh = 0
	lab var neigh "Population density"
	
esttab Model100 Model150 Model250 Model500 Model2500 using ".\inequalitypanel\results\panel_exposure_fullpanel",lab nogap base tex nomtitle star(+ 0.10 * 0.05 ** 0.01 *** 0.001) se b(%9.2f) /// 
		nomtitle replace nonotes drop(*munic* *wave*) nobaselevel ///
		refcat(1.place_fullsample#c.POOR "Poor $\times$ Exposure to poor individuals" ///
		2.unemployed_RS "Working" 2.civilstand "Widowed" 1.samboende "Living alone") ///
		stats(IFE WFE MuniFE r2 N Individual, ///
		labels("Individual FE" "Wave FE" "Municipality FE" "R-sqr(within)" "Observations" "Individuals") ///
		fmt(0 0 0 3 0 0)) ///
		mgroups("100 meter" "150 meter" "250 meter" "500 meter" "2500 meter",pattern(1 1 1 1 1) prefix(\multicolumn{@span}{c}{) suffix(}) span erepeat(\cmidrule(lr){@span})) 

		drop agecon unemp median ethdiv turnover neigh POOR enligfors //deleting labs

esttab m100 m150 m250 m500 m2500 using ".\inequalitypanel\results\panel_exposure_fullpanelmarginaleffects",replace lab nogap base tex nomtitle star(+ 0.10 * 0.05 ** 0.01 *** 0.001) se b(%9.2f) rename(1._at *Poor 2._at *Lower-Middle 3._at *Middle 4._at *Upper-Middle 5._at *Rich)

		
******MARGINAL EFFECTS
		frame copy fullpanel temp,replace
cwf temp

if 1==1 {
    glo IV indkomstplac20
	glo IVlabel Exposure to poor individuals
	glo name eksponeringfattige
	glo name2 "Exposure to poor individuals"
	mat A = [.,.,.,.,.,.,.]
	loc i = 1

foreach dist of global afst {
	xtreg redist ${IV}`dist' c.indkomstplac20`dist'#place_fullsample $ICOVAR ${ccovar`dist'} i.municip, fe robust
	margins, dydx(indkomstplac20`dist') at(place_fullsample=(4))
	mat b1 = r(table)[1,1]
	mat b2 = r(table)[5,1]
	mat b3 = r(table)[6,1]
	mat b4 = e(N)
	mat b5 = r(table)[4,1]
	loc ii = `i'
	mat b = `ii',1,b1,b2,b3,b4,b5
	mat A = A\b
	
	loc ++i
}


clear 
svmat A

drop in 1


	tw (scatter A3 A1 if A2==1, mc(black) ms(o)) (rspike A4 A5 A1 if A2==1,lc(black)) ///
	, xscal(range(0.7 9.3) extend) xlab(1 "100" 2 "150" 3 "200" 4 "250" 5 "500" 6 "1000" 7 "1500" 8 "2000" 9 "2500" ) ///
	ytit("") ysca(extend)  yline(0) name(FE_EXPOSURETOPOOR_FULLPANEL,replace) xtit("Size of Context (radius in meters)") legend(off)
	gr combine  FE_EXPOSURETOPOOR_FULLPANEL, col(1) graphregion(margin(zero) color(white))
	gr export ".\inequalitypanel\results\illustration_fullpanel.pdf",replace

}

		
		
}

	
****************************************************************************
****************TABLE A17 and ESTIMATES (NON-MOVERS) FOR FIGURE A17************************************************
*******************************************************************************
if 1==1 {
	frame change panelanalysis

	foreach dist of global afstande {

	***CONTEXT VARIABLE
	gen POOR = indkomstplac20`dist'
	gen enligfors = enligfors_`dist'

	gen agecon = agespread_`dist'
	gen unemp =unempl_narrow_`dist'
	gen median = medianinc_`dist'
	gen ethdiv = ethdiv_`dist'
	gen turnover = residentialturnover_`dist'
	gen neigh = neigh_`dist'
	global CCOVAR  agecon unemp median ethdiv turnover neigh enligfors

 	*******WITH CONTROLVARIABLES
	xtreg redist POOR c.POOR#place_primsample  $ICOVAR  $CCOVAR  if prim_sample==1 & moved!=1, fe robust
	estadd local IFE "\checkmark"
	estadd local WFE "\checkmark"
	matrix N_g = e(N_g)
	local Individual = N_g[1,1]
	estadd local Individual `Individual'
	est store Model`dist'
	
	***Marginal effects for table****
	eststo m`dist': margins, dydx(POOR) at(place_primsample=(0 1 2 3 4)) post
	
	drop POOR
	drop agecon unemp median ethdiv turnover neigh enligfors
}
	***CONTEXT VARIABLE LABELS
	gen POOR = 0
	lab var POOR "Exposure to poor individuals"

	gen agecon = 0
	lab var agecon "Age variation"

	gen unemp =0 
	lab var unemp "Share of unemployed"

	gen median = 0
	lab var median "Median income"

	gen enligfors =0 
	lab var enligfors "Share single-parent HH"
	gen ethdiv = 0
	lab var ethdiv "Ethnic diversity"

	gen turnover = 0
	lab var turnover "Residents' mobility"

	gen neigh = 0
	lab var neigh "Population density"
	
esttab Model100 Model150 Model250 Model500 Model2500 using ".\inequalitypanel\results\panel_exposure_stayers",lab nogap base nomtitle tex star(+ 0.10 * 0.05 ** 0.01 *** 0.001) se b(%9.2f) /// 
		nomtitle replace nonotes nobaselevel drop(*wave*) ///
			refcat(1.place_primsample#c.POOR "Poor $\times$ Exposure to poor individuals" ///
		2.unemployed_RS "Working" 2.civilstand "Widowed" 1.samboende "Living alone") ///
		stats(IFE WFE r2 N Individual, ///
		labels("Individual FE" "Wave FE" "R-sqr(within)" "Observations" "Individuals") ///
		fmt(0 0 3 0 0)) ///
		mgroups("100 meter" "150 meter" "250 meter" "500 meter" "2500 meter",pattern(1 1 1 1 1) prefix(\multicolumn{@span}{c}{) suffix(}) span erepeat(\cmidrule(lr){@span})) 

esttab m100 m150 m250 m500 m2500 using ".\inequalitypanel\results\panel_exposure_stayersmarginaleffects",replace lab nogap base tex nomtitle star(+ 0.10 * 0.05 ** 0.01 *** 0.001) se b(%9.2f) rename(1._at *Poor 2._at *Lower-Middle 3._at *Middle 4._at *Upper-Middle 5._at *Rich)
		
		drop agecon unemp median ethdiv turnover neigh POOR enligfors //deleting labs

************************************************
******************MARGINAL EFFECTS - COMPARE WITH OTHER MODELS************
************************************************
		frame copy panelanalysis temp,replace
cwf temp

if 1==1 {
    glo IV indkomstplac20
	glo IVlabel Exposure to poor individuals
	glo name eksponeringfattige
	glo name2 "Exposure to poor individuals"
	mat A = [.,.,.,.,.,.,.]
loc i = 1

  
foreach dist of global afst {
	***MAIN MODEL
	xtreg redist indkomstplac20`dist' c.indkomstplac20`dist'#place_primsample $ICOVAR ${ccovar`dist'} i.municip if prim_sample==1,  robust fe
	margins, dydx(indkomstplac20`dist') at(place_primsample=(4))
	mat b1 = r(table)[1,1]
	mat b2 = r(table)[5,1]
	mat b3 = r(table)[6,1]
	mat b4 = e(N)
	mat b5 = r(table)[4,1]
	loc ii = `i'
	mat b = `ii',1,b1,b2,b3,b4,b5
	mat A = A\b
	
	***EXCLUDING YOUNG
	xtreg redist incplac20_uden`dist' c.incplac20_uden`dist'#place_primsample $ICOVAR ${ccovar`dist'} i.municip  if prim_sample==1 ,  robust fe
	margins, dydx(incplac20_uden`dist') at(place_primsample=(4))
	mat b1 = r(table)[1,1]
	mat b2 = r(table)[5,1]
	mat b3 = r(table)[6,1]
	mat b4 = e(N)
	mat b5 = r(table)[4,1]
	loc ii = `i'-0.15
	mat b = `ii',2,b1,b2,b3,b4,b5
	mat A = A\b
	
	***EXCLUDING MOVERS
	xtreg redist indkomstplac20`dist' c.indkomstplac20`dist'#place_primsample $ICOVAR ${ccovar`dist'}  if prim_sample==1 & moved!=1,  robust fe
	margins, dydx(indkomstplac20`dist') at(place_primsample=(4))
	mat b1 = r(table)[1,1]
	mat b2 = r(table)[5,1]
	mat b3 = r(table)[6,1]
	mat b4 = e(N)
	mat b5 = r(table)[4,1]
	loc ii = `i'+0.15
	mat b = `ii',3,b1,b2,b3,b4,b5
	mat A = A\b
	
	*drop INEQ
	
	loc ++i
}

clear 
svmat A

drop in 1

tw (scatter A3 A1 if A2==1, mc(black) ms(o)) (rspike A4 A5 A1 if A2==1 ,lc(black)) ///
 (scatter A3 A1 if A2==2, mc(gs8) ms(o)) (rspike A4 A5 A1 if A2==2 ,lc(gs8)) ///
 (scatter A3 A1 if A2==3, mc(gs13) ms(o)) (rspike A4 A5 A1 if A2==3 ,lc(gs13)) ///
	, xscal(range(0.7 9.3) extend) xlab(1 "100" 2 "150" 3 "200" 4 "250" 5 "500" 6 "1000" 7 "1500" 8 "2000" 9 "2500" ) ///
	ytit("") ysca(extend)  yline(0) name(FE_EXPOSURETOPOOR_ROBUST,replace) xtit("Size of Context (radius in meters)") legend(position(7) ring(0) label(1 "Main Panel") label(3 "Excluding Young") label(5 "Excluding Movers") order(1 3 5))

	gr combine  FE_EXPOSURETOPOOR_ROBUST, col(1) graphregion(margin(zero) color(white))
	gr export ".\inequalitypanel\results\illustration_robst.pdf",replace


}

		
		
}
	
****************************************************************************
****************TABLE A18 AND ESTIMATES (EXCLUDING YOUNG) FOR FIGURE A17************************************************
********************************************************************************
if 1==1 {
    frame change panelanalysis

	foreach dist of global afstande {

	***CONTEXT VARIABLE
	gen POOR = incplac20_uden`dist'
	gen enligfors = enligfors_`dist'

	gen agecon = agespread_`dist'
	gen unemp =unempl_narrow_`dist'
	gen median = medianinc_`dist'
	gen ethdiv = ethdiv_`dist'
	gen turnover = residentialturnover_`dist'
	gen neigh = neigh_`dist'
	global CCOVAR  agecon unemp median ethdiv turnover neigh enligfors

 	*******WITH CONTROLVARIABLES
	xtreg redist POOR c.POOR#place_primsample  $ICOVAR  $CCOVAR i.municip if prim_sample==1, fe robust
	estadd local IFE "\checkmark"
	estadd local WFE "\checkmark"
	estadd local MuniFE "\checkmark"
	matrix N_g = e(N_g)
	local Individual = N_g[1,1]
	estadd local Individual `Individual'
	est store Model`dist'
	
	***Marginal effects for table****
	eststo m`dist': margins, dydx(POOR) at(place_primsample=(0 1 2 3 4)) post
	
	drop POOR
	drop agecon unemp median ethdiv turnover neigh enligfors
}
	
	***CONTEXT VARIABLE LABELS
	gen POOR = 0
	lab var POOR "Exposure to poor individuals"

	gen agecon = 0
	lab var agecon "Age variation"

	gen unemp =0 
	lab var unemp "Share of unemployed"

	gen median = 0
	lab var median "Median income"
	gen enligfors =0 
	lab var enligfors "Share single-parent HH"

	gen ethdiv = 0
	lab var ethdiv "Ethnic diversity"

	gen turnover = 0
	lab var turnover "Residents' mobility"

	gen neigh = 0
	lab var neigh "Population density"
	
esttab Model100 Model150 Model250 Model500 Model2500 using ".\inequalitypanel\results\panel_exposure_withoutyoung",lab nogap base tex nomtitle star(+ 0.10 * 0.05 ** 0.01 *** 0.001) se b(%9.2f) /// 
		nomtitle replace nonotes drop(*munic* *wave*) nobaselevel ///
			refcat(1.place_primsample#c.POOR "Poor $\times$ Exposure to poor individuals" ///
		2.unemployed_RS "Working" 2.civilstand "Widowed" 1.samboende "Living alone") ///
		stats(IFE WFE MuniFE r2 N Individual, ///
		labels("Individual FE" "Wave FE" "Municipality FE" "R-sqr(within)" "Observations" "Individuals") ///
		fmt(0 0 0 3 0 0)) ///
		mgroups("100 meter" "150 meter" "250 meter" "500 meter" "2500 meter",pattern(1 1 1 1 1) prefix(\multicolumn{@span}{c}{) suffix(}) span erepeat(\cmidrule(lr){@span})) 
	
esttab m100 m150 m250 m500 m2500 using ".\inequalitypanel\results\panel_exposure_withoutyoungmarginaleffects",replace lab nogap base tex nomtitle star(+ 0.10 * 0.05 ** 0.01 *** 0.001) se b(%9.2f) rename(1._at *Poor 2._at *Lower-Middle 3._at *Middle 4._at *Upper-Middle 5._at *Rich)
	
		drop agecon unemp median ethdiv turnover neigh POOR enligfors //deleting labs
		
}

*******************************************************************************
******************FIGURE A18: DIFFERENT SAMPLE RESTRICTIONS (No. Neighbors)*********
********************************************************************************
if 1==1 {
    glo IV indkomstplac20
	glo IVlabel Exposure to Poor
	glo name eksponeringfattige
	glo name2 "Exposure to poor individuals"
	mat A = [.,.,.,.,.,.,.]
	loc i = 1

*******************************************************************************
******************PANEL ESTIMATES WITHOUT Neighbor RESTRICTION*********
********************************************************************************
frame create panel_norestriction
frame change panel_norestriction

use "E:\workdata\702992\702992\Matias\inequalitypanel\Poor_rich_dofiles\panelsample_noneighborrestriction.dta",clear
frame copy panel_norestriction temp,replace
cwf temp


 
foreach dist of global afst {
	xtreg redist ${IV}`dist' c.indkomstplac20`dist'#place_primsample $ICOVAR ${ccovar`dist'} i.municip if prim_sample==1,  robust fe
	margins, dydx(indkomstplac20`dist') at(place_primsample=(4))
	mat b1 = r(table)[1,1]
	mat b2 = r(table)[5,1]
	mat b3 = r(table)[6,1]
	mat b4 = e(N)
	mat b5 = r(table)[4,1]
	loc ii = `i'-0.3
	mat b = `ii',1,b1,b2,b3,b4,b5
	mat A = A\b
	
	*drop INEQ
	
	loc ++i
}

	loc i = 1

*******************************************************************************
******************PANEL ESTIMATES FIVE Neighbor RESTRICTION*********
********************************************************************************
frame create panel_restriction5
frame change panel_restriction5

use "E:\workdata\702992\702992\Matias\inequalitypanel\Poor_rich_dofiles\panelsample_5neighborrestriction.dta",clear
frame copy panel_restriction5 temp,replace
cwf temp


foreach dist of global afst {
	xtreg redist ${IV}`dist' c.indkomstplac20`dist'#place_primsample $ICOVAR ${ccovar`dist'} i.municip if prim_sample==1,  robust fe
	margins, dydx(indkomstplac20`dist') at(place_primsample=(4))
	mat b1 = r(table)[1,1]
	mat b2 = r(table)[5,1]
	mat b3 = r(table)[6,1]
	mat b4 = e(N)
	mat b5 = r(table)[4,1]
	loc ii = `i'-0.2
	mat b = `ii',2,b1,b2,b3,b4,b5
	mat A = A\b
	
	*drop INEQ
	
	loc ++i
}

loc i = 1

*******************************************************************************
******************PANEL ESTIMATES TEN Neighbor RESTRICTION*********
********************************************************************************
frame create panel_restriction10
frame change panel_restriction10

use "E:\workdata\702992\702992\Matias\inequalitypanel\Poor_rich_dofiles\panelsample_10neighborrestriction.dta",clear
frame copy panel_restriction10 temp,replace
cwf temp


foreach dist of global afst {
	xtreg redist ${IV}`dist' c.indkomstplac20`dist'#place_primsample $ICOVAR ${ccovar`dist'} i.municip if prim_sample==1  ,  robust fe
	margins, dydx(indkomstplac20`dist') at(place_primsample=(4))
	mat b1 = r(table)[1,1]
	mat b2 = r(table)[5,1]
	mat b3 = r(table)[6,1]
	mat b4 = e(N)
	mat b5 = r(table)[4,1]
	loc ii = `i'-0.1
	mat b = `ii',3,b1,b2,b3,b4,b5
	mat A = A\b
	
	*drop INEQ
	
	loc ++i
}

loc i = 1

*******************************************************************************
******************PANEL ESTIMATES BASED ON PRIMARY SAMPLE*********
********************************************************************************
frame copy panelanalysis temp,replace
cwf temp

foreach dist of global afst {
	xtreg redist ${IV}`dist' c.indkomstplac20`dist'#place_primsample $ICOVAR ${ccovar`dist'} i.municip if prim_sample==1 ,  robust fe
	margins, dydx(indkomstplac20`dist') at(place_primsample=(4))
	mat b1 = r(table)[1,1]
	mat b2 = r(table)[5,1]
	mat b3 = r(table)[6,1]
	mat b4 = e(N)
	mat b5 = r(table)[4,1]
	loc ii = `i'
	mat b = `ii',4,b1,b2,b3,b4,b5
	mat A = A\b
	
	*drop INEQ
	
	loc ++i
}

loc i = 1

*******************************************************************************
******************PANEL ESTIMATES TWENTY Neighbor RESTRICTION*********
********************************************************************************
frame create panel_restriction20
frame change panel_restriction20

use "E:\workdata\702992\702992\Matias\inequalitypanel\Poor_rich_dofiles\panelsample_20neighborrestriction.dta",clear
frame copy panel_restriction20 temp,replace
cwf temp

foreach dist of global afst {
	xtreg redist ${IV}`dist' c.indkomstplac20`dist'#place_primsample $ICOVAR ${ccovar`dist'} i.municip if prim_sample==1  ,  robust fe
	margins, dydx(indkomstplac20`dist') at(place_primsample=(4))
	mat b1 = r(table)[1,1]
	mat b2 = r(table)[5,1]
	mat b3 = r(table)[6,1]
	mat b4 = e(N)
	mat b5 = r(table)[4,1]
	loc ii = `i'+0.1
	mat b = `ii',5,b1,b2,b3,b4,b5
	mat A = A\b
	
	*drop INEQ
	
	loc ++i
}

loc i = 1

*******************************************************************************
******************PANEL ESTIMATES TWENTY Neighbor RESTRICTION*********
********************************************************************************
frame create panel_restriction25
frame change panel_restriction25

use "E:\workdata\702992\702992\Matias\inequalitypanel\Poor_rich_dofiles\panelsample_25neighborrestriction.dta",clear
frame copy panel_restriction25 temp,replace
cwf temp

foreach dist of global afst {
	xtreg redist ${IV}`dist' c.indkomstplac20`dist'#place_primsample $ICOVAR ${ccovar`dist'} i.municip if prim_sample==1  ,  robust fe
	margins, dydx(indkomstplac20`dist') at(place_primsample=(4))
	mat b1 = r(table)[1,1]
	mat b2 = r(table)[5,1]
	mat b3 = r(table)[6,1]
	mat b4 = e(N)
	mat b5 = r(table)[4,1]
	loc ii = `i'+0.2
	mat b = `ii',6,b1,b2,b3,b4,b5
	mat A = A\b
	
	*drop INEQ
	
	loc ++i
}

*******************************************************************************
******************MAKING ILLUSTRATION*********
********************************************************************************

clear 
svmat A

drop in 1



tw (scatter A3 A1 if A2==1 , mc(gs14) ms(o))  ///
	(rspike A4 A5 A1 if A2==1 ,lc(gs14)) ///
	(scatter A3 A1 if A2==2 , mc(gs12) ms(o))  ///
	(rspike A4 A5 A1 if A2==2 ,lc(gs12)) ///
	(scatter A3 A1 if A2==3 , mc(gs10) ms(o))  ///
	(rspike A4 A5 A1 if A2==3 ,lc(gs10)) ///
	(scatter A3 A1 if A2==4 , mc(black) ms(o))  ///
	(rspike A4 A5 A1 if A2==4 ,lc(black)) ///
	(scatter A3 A1 if A2==5, mc(gs8) ms(o))  ///
	(rspike A4 A5 A1 if A2==5 ,lc(gs8)) ///
	(scatter A3 A1 if A2==6 , mc(gs6) ms(o))  ///
	(rspike A4 A5 A1 if A2==6 ,lc(gs6)) ///
	, xscal(range(0.7 9.3) extend) xlab(1 "100" 2 "150" 3 "200" 4 "250" 5 "500" 6 "1000" 7 "1500" 8 "2000" 9 "2500") ///
	ytit("") ysca(extend)  yline(0) name(FE_EXPOSURETOPOOR_compare,replace) legend(position(11) ring(0) label(11 ">= 25 Neighbors") label(9 ">= 20 Neighbors") label(7 "Primary Panel Estimate") label(5 ">= 10 Neighbors") label(3 ">= 5 Neighbors") label(1 "No Restriction on No. of Neighbors") order(1 3 5 7 9 11))  xtit("Size of Context (radius in meters)") title("")

gr combine FE_EXPOSURETOPOOR_compare,  graphregion(margin(zero) color(white))

gr export ".\inequalitypanel\results\primaryillustra_withoutneigh_res.pdf",replace

}


********************************************************************************
******************FIGURE A19: WITHOUT TIME AS A RESTRICTION**********************
********************************************************************************
if 1==1 {

frame create withouttime
frame change withouttime

use "E:\workdata\702992\702992\Matias\inequalitypanel\Poor_rich_dofiles\panelsample_withouttimeasrestriction.dta",clear

****************************************************************************
****************SETTING UP FIGURE************************************************
********************************************************************************


if 1==1 {
    frame copy withouttime temp,replace
	cwf temp

	glo IV indkomstplac20
	glo IVlabel Exposure to Poor
	glo name eksponeringfattige
	glo name2 "Exposure to poor individuals"
	mat A = [.,.,.,.,.,.,.]
	loc i = 1


****************************************************************************
****************ESTIMATES WITHOUT RESTRICTION***********************************
******************************************************************************** 
foreach dist of global afst {
	xtreg redist ${IV}`dist' c.indkomstplac20`dist'#place_primsample $ICOVAR ${ccovar`dist'} i.municip if prim_sample==1,  robust fe
	margins, dydx(indkomstplac20`dist') at(place_primsample=(4))
	mat b1 = r(table)[1,1]
	mat b2 = r(table)[5,1]
	mat b3 = r(table)[6,1]
	mat b4 = e(N)
	mat b5 = r(table)[4,1]
	loc ii = `i'-0.1
	mat b = `ii',1,b1,b2,b3,b4,b5
	mat A = A\b
	
	*drop INEQ
	
	loc ++i
}

	loc i = 1


****************************************************************************
****************ESTIMATES WITH RESTRICTION***********************************
********************************************************************************
frame copy panelanalysis temp,replace
cwf temp

foreach dist of global afst {
	xtreg redist ${IV}`dist' c.indkomstplac20`dist'#place_primsample $ICOVAR ${ccovar`dist'} i.municip if prim_sample==1,  robust fe
	margins, dydx(indkomstplac20`dist') at(place_primsample=(4))
	mat b1 = r(table)[1,1]
	mat b2 = r(table)[5,1]
	mat b3 = r(table)[6,1]
	mat b4 = e(N)
	mat b5 = r(table)[4,1]
	loc ii = `i'+0.1
	mat b = `ii',2,b1,b2,b3,b4,b5
	mat A = A\b
	
	*drop INEQ
	
	loc ++i
}


clear 
svmat A

drop in 1


****************************************************************************
****************MAKING FIGURE************************************************
********************************************************************************
tw (scatter A3 A1 if A2==1 , mc(gs12) ms(o))  ///
	(rspike A4 A5 A1 if A2==1 ,lc(gs12)) ///
	(scatter A3 A1 if A2==2 , mc(black) ms(o))  ///
	(rspike A4 A5 A1 if A2==2 ,lc(black)) ///
	, xscal(range(0.7 9.3) extend) xlab(1 "100" 2 "150" 3 "200" 4 "250" 5 "500" 6 "1000" 7 "1500" 8 "2000" 9 "2500") ///
	ytit("") ysca(extend)  yline(0) name(FE_EXPOSURETOPOOR_compare,replace) legend(position(11) ring(0) label(3 "Primary Panel Estimate") label(1 "Panel Estimate without Length of Stay Restriction") order(1 3))  xtit("Size of Context (radius in meters)") title("")

gr combine FE_EXPOSURETOPOOR_compare,  graphregion(margin(zero) color(white))

gr export ".\inequalitypanel\results\primaryillustra_withoutstay_res.pdf",replace

}
}

********************************************************************************
****************SECTION D.4************************************************
****************************************************************************
************************************************************************************
****************FIGURE A21: PROBING PARALELL TRENDS****************************
************************************************************************************
if 1==1 {
	
frame change panelanalysis
set scheme plotplain
graph set window fontface "Times New Roman"
frame copy panelanalysis temp,replace
cwf temp

xtset id wave
drop temp2

***Making variable to probe parallell trend assumption
gen temp_ekspwave3=indkomstplac20100 if wave==3 //exposure to poor in wave 3
egen eks_wave3 =max(temp_ekspwave3),by(id)

gen probe_parallel = eks_wave3 if wave==2 & eks_wave3!=. 

gen temp_ekspwave2=indkomstplac20100 if wave==2 //exposure to poor in wave 2
egen eks_wave2 =max(temp_ekspwave2),by(id)

replace probe_parallel = eks_wave2 if wave==1 & eks_wave3!=.

***Flexible exposure
gen temp2_ekspwave3=exposure_weigthed100 if wave==3 //flexible exposure to poor in wave 3
egen eks2_wave3 =max(temp2_ekspwave3),by(id)

gen probe_parallel_flex = eks2_wave3 if wave==2 & eks2_wave3!=.

gen temp2_ekspwave2=exposure_weigthed100 if wave==2 //flexible exposure to poor in wave 2
egen eks2_wave2 =max(temp2_ekspwave2),by(id)

replace probe_parallel_flex = eks2_wave2 if wave==1 & eks2_wave3!=.

***making control variables to dummies for FD estimations
recode unemployed_R (1=1) (else=0), gen(iarbejde)
recode unemployed_R (2=1) (else=0), gen(arbejdslos)
recode unemployed_R (3=1) (else=0), gen(pensionist)
recode unemployed_R (4=1) (else=0), gen(fortidspensionist)
recode unemployed_R (5=1) (else=0), gen(studerende)

recode civilstand (1=1) (else=0), gen(widow)
recode civilstand (2=1) (else=0), gen(divorced)
recode civilstand (3=1) (else=0), gen(married)
recode civilstand (4=1) (else=0), gen(unmarried)

recode wave (1=1) (else=0),gen(wave1)
recode wave (2=1) (else=0),gen(wave2)

tab municip if wave!=3 & place_primsample==4 & prim_sample==1, gen(municip_)


foreach var of varlist municip_* {
	gen delta_`var' = d.`var'
}


if 1==1 {

	glo name2 "Exposure to poor individuals"
	mat A = [.,.,.,.,.,.,.]
	loc i = 1


	**FD WITH STANDARD EXPOSURE
	reg d.probe_parallel d.redist d.indkomstplac20100 d.hhi_ln d.neigh_100 d.civilstand delta_m* d.wave d.medianinc_100 d.unempl_narrow_100 d.iarbejde d.arbejdslos d.pensionist d.fortidspensionist d.studerende d.yearslived d.EduYearsRS d.residentialturnover_100 d.samboende d.agespread_100 d.ethdiv_100 d.enligfors_100 if place_primsample==4 & prim_sample==1  & count2==3, robust nocons //FD
	margins, dydx(D1.redist)

	mat b1 = r(table)[1,1]
	mat b2 = r(table)[5,1]
	mat b3 = r(table)[6,1]
	mat b4 = e(N)
	mat b5 = r(table)[4,1]
	loc ii = 1.7
	mat b = 1.7,1,b1,b2,b3,b4,b5
	mat A = A\b
	
	**XTREG WITH STANDARD EXPOSURE
	xtreg probe_parallel redist indkomstplac20100 $ccovar100 $ICOVAR i.municip if place_primsample==4 & prim_sample==1 & count2==3,fe robust //XTREG
	margins, dydx(redist)

	mat b1 = r(table)[1,1]
	mat b2 = r(table)[5,1]
	mat b3 = r(table)[6,1]
	mat b4 = e(N)
	mat b5 = r(table)[4,1]
	loc ii = 1.2
	mat b = 1.2,1,b1,b2,b3,b4,b5
	mat A = A\b
	
	loc ++i

	*FD  WITH FLEX. EXPOSURE
	reg d.probe_parallel_flex d.redist d.exposure_weigthed100 d.hhi_ln d.neigh_100 d.civilstand delta_muni* d.wave d.medianinc_100 d.unempl_narrow_100 d.iarbejde d.arbejdslos d.pensionist d.fortidspensionist d.studerende d.yearslived d.EduYearsRS d.residentialturnover_100 d.samboende d.agespread_100 d.ethdiv_100 d.enligfors_100 if place_primsample==4 & prim_sample==1 & count2==3,robust nocons //FD
	margins, dydx(D1.redist)

		mat b1 = r(table)[1,1]
	mat b2 = r(table)[5,1]
	mat b3 = r(table)[6,1]
	mat b4 = e(N)
	mat b5 = r(table)[4,1]
	loc ii = 1.8
	mat b = 1.8,2,b1,b2,b3,b4,b5
	mat A = A\b
	
	**XTREG WITH FLEX. EXPOSURE
	xtreg probe_parallel_flex redist exposure_weigthed100 $ccovar100 $ICOVAR i.municip  if  place_primsample==4 & prim_sample==1  & count2==3,fe robust //XTREG
	margins, dydx(redist)

	mat b1 = r(table)[1,1]
	mat b2 = r(table)[5,1]
	mat b3 = r(table)[6,1]
	mat b4 = e(N)
	mat b5 = r(table)[4,1]
	loc ii = 1.3
	mat b = 1.3,2,b1,b2,b3,b4,b5
	mat A = A\b


clear 
svmat A

drop in 1

tw (scatter A3 A1 if A2==1, mc(black) ms(o)) (rspike A4 A5 A1 if A2==1 ,lc(black)) ///
 (scatter A3 A1 if A2==2, mc(gs13) ms(o)) (rspike A4 A5 A1 if A2==2 ,lc(gs13)) ///
	, xscal(range(1 2) extend) xlab(1.25 "Mean Deviation" 1.75 "First Difference" ) ytit("") ///
	title("") ysca(extend)  yline(0) name(PROBING_PARALLEL_TREND,replace) xtit("") legend(position(7) ring(0) label(1 "Dependent variable: Std. Exposure Measure") label(3 "Dependent variable: Gradual Exposure Measure") order(1 3))

	gr combine  PROBING_PARALLEL_TREND, col(1)  graphregion(margin(zero) color(white))
	gr export ".\inequalitypanel\results\PROBING_PARALLEL_TREND.pdf",replace


}
}


********************************************************************************
****************SECTION D.5************************************************
****************************************************************************
****************************************************************************
****************TABLE A19 and FIGURE A23: INTERACTION EFFECT OF IDEOLOGY*******
********************************************************************************
if 1==1 {
	
frame copy panelanalysis temp,replace
cwf temp

xtreg redist indkomstplac20100 c.indkomstplac20100#place_primsample c.indkomstplac20100#c.ideo_wave1 c.indkomstplac20100#place_primsample#c.ideo_wave1 $ICOVAR $ccovar100 i.municip if prim_sample==1, fe robust
estadd local Waves "Three"
	estadd local IFE "\checkmark"
	estadd local WFE "\checkmark"
	estadd local MuniFE "\checkmark"
	estadd local IC "\checkmark"
	estadd local CC "\checkmark"
	matrix N_g = e(N_g)
	local Individual = N_g[1,1]
	estadd local Individual `Individual'
	est store Model_ideoinact_all

	eststo m_normal: margins, dydx(indkomstplac20100) at(ideo_wave1=(0 (1)10 ) place_primsample=(0 1 2 3 4)) post

	
xtreg redist indkomstplac20100 c.indkomstplac20100#c.ideo_wave1 $ICOVAR $ccovar100 i.municip if prim_sample==1 & place_primsample==4, fe robust 
estadd local Waves "Three"
	estadd local IFE "\checkmark"
	estadd local WFE "\checkmark"
	estadd local MuniFE "\checkmark"
	estadd local IC "\checkmark"
	estadd local CC "\checkmark"
	matrix N_g = e(N_g)
	local Individual = N_g[1,1]
	estadd local Individual `Individual'
	est store Model_ideoinact_rich
	
	
xtreg redist indkomstplac20100 c.indkomstplac20100#c.ideo_wave1 $ICOVAR $ccovar100 i.municip if prim_sample==1 & place_primsample==4, fe robust 
margins, dydx(indkomstplac20100) at(ideo_wave1=(0 (1) 10)) saving(.\inequalitypanel\results\marginsplot_ideologyinterac, replace)
	
frame create marginsplot_ideologyinterac
cwf marginsplot_ideologyinterac
	
	use .\inequalitypanel\results\marginsplot_ideologyinterac, clear
	
	twoway (rspike _ci_lb _ci_ub _at, sort pstyle(ci) lcolor("black")) ///
		(scatter _margin _at ,sort mc("black") msymbol(o)) , ///
		xscale(range(0.5 11.5)) yline(0) yscale(range(-5 5))  ylabel(-5 (1) 5) xlab(1 "Left-Wing" 6 "Middle" 11 "Right-Wing") xtitle("Political Ideology") ytitle("Marginal Effect of Exposure to Poor Individuals") title("Panel A: Marginal Effect of Exposure Across Political Ideology among the Rich") legend(off) name(interaction_ideo,replace)
	

cwf temp

}

****************************************************************************
****************TABLE A19 and FIGURE A23: EFFECT ON IDEOLOGY**************
********************************************************************************
if 1==1 {
	
xtreg gammelskala indkomstplac20100 c.indkomstplac20100#place_primsample $ICOVAR $ccovar100 i.municip if prim_sample==1, fe robust
estadd local Waves "Two"
	estadd local IFE "\checkmark"
	estadd local WFE "\checkmark"
	estadd local MuniFE "\checkmark"
	estadd local IC "\checkmark"
	estadd local CC "\checkmark"
	matrix N_g = e(N_g)
	local Individual = N_g[1,1]
	estadd local Individual `Individual'
	est store Model_ideooutcome_all
	
eststo m_politicaloutcome: margins, dydx(indkomstplac20100) at(place_primsample=(0 1 2 3 4)) post

xtreg gammelskala indkomstplac20100 $ICOVAR $ccovar100 i.municip if prim_sample==1 & place_primsample==4, fe robust 
estadd local Waves "Two"
	estadd local IFE "\checkmark"
	estadd local WFE "\checkmark"
	estadd local MuniFE "\checkmark"
	estadd local IC "\checkmark"
	estadd local CC "\checkmark"
	matrix N_g = e(N_g)
	local Individual = N_g[1,1]
	estadd local Individual `Individual'
	est store Model_ideooutcome_rich

	
xtreg gammelskala indkomstplac20100 $ICOVAR $ccovar100 i.municip if prim_sample==1 & place_primsample==4, fe robust 
margins, dydx(indkomstplac20100) saving(.\inequalitypanel\results\marginsplot_ideologyoutcome, replace)
	
frame create marginsplot_ideologyoutcome
cwf marginsplot_ideologyoutcome
	
	use .\inequalitypanel\results\marginsplot_ideologyoutcome, clear
	
	twoway(rspike _ci_lb _ci_ub _deriv, sort pstyle(ci) lcolor("black")) ///
		(scatter _margin _deriv,sort mc("black") msymbol(o)), ///
		 yline(0) yscale(range(-5 5))  ylabel(-5 (1) 5) xlab(,nolab) xtitle("Exposure to Poor Individuals") ytitle("Marginal Effect of Exposure to Poor Individuals") title("Panel B: Marginal Effect of Exposure on Political Ideology among the Rich") legend(off) name(ideo_outcome,replace)
	

cwf temp
	
		gr combine interaction_ideo ideo_outcome, col(1) ysize(10) graphregion(margin(zero) color(white))
	gr export ".\inequalitypanel\results\political_ideology.pdf",replace

	
esttab Model_ideoinact_all Model_ideooutcome_all Model_ideoinact_rich Model_ideooutcome_rich using ".\inequalitypanel\results\panel_exposure_ideointeraction",lab nogap base wide tex star(+ 0.10 * 0.05 ** 0.01 *** 0.001) se b(%9.2f) /// 
	 replace nonotes drop(*muni* *.wave*) nobaselevel ///
		refcat(c.ideo_wave1#c.indkomstplac20100 "Exposure to poor Individuals $\times$ Political Ideology" 1.place_primsample#c.indkomstplac20100 "Poor $\times$ Exposure to poor individuals" ///
		1.place_primsample#c.indkomstplac20100#c.ideo_wave1 "Poor $\times$ Exposure to poor individuals $\times$ Political Ideology"  ///
		2.unemployed_RS "Working" 2.civilstand "Widowed" 1.samboende "Living alone") ///
		stats(IFE WFE MuniFE IC CC Waves r2 N Individual, ///
		labels("Individual FE" "Wave FE" "Municipality FE" "Individual Controls" "Contextual Controls" "Waves" "R-sqr(within)" "Observations" "Individuals") ///
		fmt(0 0 0 0 0 0 3 0 0)) ///
		mtitles("Interaction Model" "Political Ideology as Outcome" "Interaction Model" "Political Ideology as Outcome") ///
		mgroups("Full Sample" "Only Rich Sample",pattern(1 0 1 0) prefix(\multicolumn{@span}{c}{) suffix(}) span erepeat(\cmidrule(lr){@span})) 

	esttab m_politicaloutcome using ".\inequalitypanel\results\panel_exposure_ideologymarginaleffects",replace lab nogap base tex nomtitle star(+ 0.10 * 0.05 ** 0.01 *** 0.001) se b(%9.2f) rename(1._at *Poor 2._at *Lower-Middle 3._at *Middle 4._at *Upper-Middle 5._at *Rich)

}
		

********************************************************************************
****************FIGURE A22: NEGATIVE AND POSITIVE CHANGES**********************************
********************************************************************************
if 1==1 {
	

frame change panelanalysis
set scheme plotplain
graph set window fontface "Times New Roman"
frame copy panelanalysis temp,replace
cwf temp

foreach dist of global afst {
   xtset id wave
gen delta`dist' = d.indkomstplac20`dist'

replace delta`dist'=0 if delta`dist'==.

gen positive`dist' = delta`dist'* (delta`dist'>0)
gen negative`dist' =  delta`dist'* (delta`dist'<0)

gen sumpositive`dist' = positive`dist' + L1.positive`dist' if wave==3
replace sumpositive`dist' = positive`dist' if wave==2
replace sumpositive`dist' = 0 if wave==1

gen sumnegative`dist' = negative`dist' + L1.negative`dist' if wave==3
replace sumnegative`dist' = negative`dist' if wave==2
replace sumnegative`dist' = 0 if wave==1

}


if 1==1 {
    glo IV indkomstplac20
	glo IVlabel Exposure to poor individuals
	glo name eksponeringfattige
	glo name2 "Exposure to poor individuals"
	mat A = [.,.,.,.,.,.,.]
	loc i = 1

  
foreach dist of global afst {
    
	**NEGATIVE CHANGES
	xtreg redist c.sumnegative`dist' c.sumnegative`dist'#place_primsample c.sumpositive`dist' c.sumpositive`dist'#place_primsample $ICOVAR ${ccovar`dist'} i.municip if prim_sample==1,  robust fe
	margins, dydx(sumnegative`dist') at(place_primsample=(4))
	mat b1 = r(table)[1,1]
	mat b2 = r(table)[5,1]
	mat b3 = r(table)[6,1]
	mat b4 = e(N)
	mat b5 = r(table)[4,1]
	loc ii = `i'-0.1
	mat b = `ii',1,b1,b2,b3,b4,b5
	mat A = A\b
	
	**POSITIVE CHANGES
xtreg redist c.sumnegative`dist' c.sumnegative`dist'#place_primsample c.sumpositive`dist' c.sumpositive`dist'#place_primsample $ICOVAR ${ccovar`dist'} i.municip if prim_sample==1,  robust fe
	margins, dydx(sumpositive`dist') at(place_primsample=(4))
	mat b1 = r(table)[1,1]
	mat b2 = r(table)[5,1]
	mat b3 = r(table)[6,1]
	mat b4 = e(N)
	mat b5 = r(table)[4,1]
	loc ii = `i'+0.1
	mat b = `ii',2,b1,b2,b3,b4,b5
	mat A = A\b
	
	*drop INEQ
	
	loc ++i

}


clear 
svmat A

drop in 1

tw (scatter A3 A1 if A2==1, mc(black) ms(o)) (rspike A4 A5 A1 if A2==1 ,lc(black)) ///
 (scatter A3 A1 if A2==2, mc(gs13) ms(o)) (rspike A4 A5 A1 if A2==2 ,lc(gs13)) ///
	, xscal(range(0.7 9.3) extend) xlab(1 "100" 2 "150" 3 "200" 4 "250" 5 "500" 6 "1000" 7 "1500" 8 "2000" 9 "2500" ) ///
	ytit("") ysca(extend)  yline(0) name(FE_EXPOSURETOPOOR_NEGA_POSI,replace) xtit("Size of Context (radius in meters)") legend(position(7) ring(0) label(1 "Negative Changes") label(3 "Positive Changes") order(1 3))

	gr combine  FE_EXPOSURETOPOOR_NEGA_POSI, col(1) graphregion(margin(zero) color(white))
	gr export ".\inequalitypanel\results\negative_positive.pdf",replace


}


}

****************************************************************************
****************FIGURE A25: AFFECTING IMMIGRANT ATTITUDES?************************************************
********************************************************************************
if 1==1 {
	
frame copy panelanalysis temp,replace
cwf temp

xtreg culture_immi indkomstplac20100 c.indkomstplac20100#place_primsample $ICOVAR $ccovar100 i.municip if prim_sample==1, fe robust //whether immigrants enrich or undermine

	margins, dydx(indkomstplac20100) at(place_primsample=(0 1 2 3 4)) saving(.\inequalitypanel\results\marginsplot_enrich, replace)
	
	frame create marginsplot_enrich
	cwf marginsplot_enrich
	
	use .\inequalitypanel\results\marginsplot_enrich, clear
	
	twoway (rspike _ci_lb _ci_ub _at if _at!=5, sort pstyle(ci) lcolor("gray")) ///
		(rspike _ci_lb _ci_ub _at if _at==5, sort pstyle(ci) lcolor("black")) ///
		(scatter _margin _at if _at!=5,sort mc("gray") msymbol(o))  ///
		(scatter _margin _at if _at==5,sort mc("black") msymbol(o)) , ///
		 yline(0) yscale(range(-10 10))  ylabel(-10 (2) 10) xlab(1 "Poor" 2 "Lower-Middle" 3 "Middle" 4 "Upper-Middle" 5 "Rich") xtitle("Income Group") ytitle("Marginal Effect of Exposure to Poor Individuals") title("Panel A: Cultural Life is Enrich by Immigrants") legend(off) name(culturallife,replace)
	

cwf temp


xtreg contribu_immi indkomstplac20100 c.indkomstplac20100#place_primsample $ICOVAR $ccovar100 i.municip if prim_sample==1, fe robust //whether immigrants contribute to the economy 
	margins, dydx(indkomstplac20100) at(place_primsample=(0 1 2 3 4)) saving(.\inequalitypanel\results\marginsplot_contribute, replace)
	
	frame create marginsplot_contribute
	cwf marginsplot_contribute
	
	use .\inequalitypanel\results\marginsplot_contribute, clear
	
	twoway (rspike _ci_lb _ci_ub _at if _at!=5, sort pstyle(ci) lcolor("gray")) ///
		(rspike _ci_lb _ci_ub _at if _at==5, sort pstyle(ci) lcolor("black")) ///
		(scatter _margin _at if _at!=5,sort mc("gray") msymbol(o))  ///
		(scatter _margin _at if _at==5,sort mc("black") msymbol(o)) , ///
		yline(0) yscale(range(-10 10))  ylabel(-10 (2) 10)  xlab(1 "Poor" 2 "Lower-Middle" 3 "Middle" 4 "Upper-Middle" 5 "Rich") xtitle("Income Group") ytitle("Marginal Effect of Exposure to Poor Individuals") title("Panel B: Does Immigrants Contribute more than they Receive") legend(off) name(contribute,replace)
	

cwf temp
	gr combine culturallife contribute, col(1) ysize(10) graphregion(margin(zero) color(white))
	gr export ".\inequalitypanel\results\PLACEBO_TEST.pdf",replace

}
	

****************************************************************************
****************SECTION E in APPENDIX************************************************
********************************************************************************
frame change panelanalysis

if 1==1 {
	
****************************************************************************
****************MAKING TABLE A20************************************************
********************************************************************************
	foreach dist of global afstande {

	***CONTEXT VARIABLE
	gen RICH = indkomstplac80`dist'
	gen enligfors = enligfors_`dist'

	gen agecon = agespread_`dist'
	gen unemp =unempl_narrow_`dist'
	gen median = medianinc_`dist'
	gen ethdiv = ethdiv_`dist'
	gen turnover = residentialturnover_`dist'
	gen neigh = neigh_`dist'
	global CCOVAR  agecon unemp median ethdiv turnover neigh enligfors

 	*******WITH CONTROLVARIABLES
	xtreg redist RICH c.RICH#place_primsample $ICOVAR  $CCOVAR i.municip if prim_sample==1, fe robust
	estadd local IFE "\checkmark"
	estadd local WFE "\checkmark"
	estadd local MuniFE "\checkmark"
	matrix N_g = e(N_g)
	local Individual = N_g[1,1]
	estadd local Individual `Individual'
	est store Model`dist'
	
	***Marginal effects for table****
	eststo m`dist': margins, dydx(RICH) at(place_primsample=(0 1 2 3 4)) post
	
	
	drop RICH
	drop agecon unemp median ethdiv turnover neigh enligfors
}


	***CONTEXT VARIABLE LABELS
	gen RICH = 0
	lab var RICH "Exposure to rich individuals"

	gen agecon = 0
	lab var agecon "Age variation"

	gen unemp =0 
	lab var unemp "Share of unemployed"

	gen median = 0
	lab var median "Median income"
	gen enligfors =0 
	lab var enligfors "Share single-parent HH"

	gen ethdiv = 0
	lab var ethdiv "Ethnic diversity"

	gen turnover = 0
	lab var turnover "Residents' mobility"

	gen neigh = 0
	lab var neigh "Population density"
	
esttab Model100 Model150 Model250 Model500 Model2500 using ".\inequalitypanel\results\panel_exposuretorich",lab nogap base tex nomtitle star(+ 0.10 * 0.05 ** 0.01 *** 0.001) se b(%9.2f) /// 
		nomtitle replace nonotes drop(*munic* *wave*) nobaselevel ///
			refcat(1.place_primsample#c.RICH "Poor $\times$ Exposure to rich individuals" ///
		2.unemployed_RS "Working" 2.civilstand "Widowed"  1.samboende "Living alone") ///
		stats(IFE WFE MuniFE r2 N Individual, ///
		labels("Individual FE" "Wave FE" "Municipality FE" "R-sqr(within)" "Observations" "Individuals") ///
		fmt(0 0 0 3 0 0)) ///
		mgroups("100 meter" "150 meter" "250 meter" "500 meter" "2500 meter",pattern(1 1 1 1 1) prefix(\multicolumn{@span}{c}{) suffix(}) span erepeat(\cmidrule(lr){@span})) 
		
		esttab m100 m150 m250 m500 m2500 using ".\inequalitypanel\results\panel_exposure_richexposure_marginaleffects",replace lab nogap base tex nomtitle star(+ 0.10 * 0.05 ** 0.01 *** 0.001) se b(%9.2f) rename(1._at *Poor 2._at *Lower-Middle 3._at *Middle 4._at *Upper-Middle 5._at *Rich)

		
		drop agecon unemp median ethdiv turnover neigh RICH enligfors //deleting labs

****************************************************************************
****************FIGURE A26******
********************************************************************************
		frame copy panelanalysis temp,replace
cwf temp

if 1==1 {
    glo IV indkomstplac80
	glo IVlabel Exposure to Rich
	glo name eksponeringrige
	glo name2 "Exposure to Rich"
	mat A = [.,.,.,.,.,.]
loc i = 1

****************************************************************************
****************ESTIMATING EFFECTS FOR THE POOR (UPPER PANEL OF FIGURE A26)******
********************************************************************************
foreach dist of global afst {
	
	****FULL SAMPLE
	xtreg redist indkomstplac80`dist' c.indkomstplac80`dist'#place_primsample $ICOVAR ${ccovar`dist'} i.municip if prim_sample==1 ,  robust fe
	margins, dydx(indkomstplac80`dist') at(place_primsample=(0))
	mat b1 = r(table)[1,1]
	mat b2 = r(table)[5,1]
	mat b3 = r(table)[6,1]
	mat b4 = e(N)
	loc ii = `i'-0.15
	mat b = `ii',1,b1,b2,b3,b4
	mat A = A\b

	****FULL SAMPLE+CONTROL FOR SHARE OF POOR
	xtreg redist indkomstplac80`dist' c.indkomstplac80`dist'#place_primsample indkomstplac20`dist' c.indkomstplac20`dist'#place_primsample $ICOVAR ${ccovar`dist'} i.municip if prim_sample==1 ,  robust fe
	margins, dydx(indkomstplac80`dist') at(place_primsample=(0))
	mat b1 = r(table)[1,1]
	mat b2 = r(table)[5,1]
	mat b3 = r(table)[6,1]
	mat b4 = e(N)
	loc ii = `i'-0.05
	mat b = `ii',2,b1,b2,b3,b4
	mat A = A\b
	
	***EXCLUDING MOVERS
	xtreg redist indkomstplac80`dist' c.indkomstplac80`dist'#place_primsample $ICOVAR ${ccovar`dist'}  if prim_sample==1 & moved!=1,  robust fe
	margins, dydx(indkomstplac80`dist') at(place_primsample=(0))
	mat b1 = r(table)[1,1]
	mat b2 = r(table)[5,1]
	mat b3 = r(table)[6,1]
	mat b4 = e(N)
	mat b5 = r(table)[4,1]
	loc ii = `i'+0.05
	mat b = `ii',3,b1,b2,b3,b4
	mat A = A\b
	
	***RESTRICTING TO SAMPLE OF POOR RESPONDENTS
	xtreg redist indkomstplac80`dist' $ICOVAR ${ccovar`dist'}  if prim_sample==1 & place_primsample==0,  robust fe
	margins, dydx(indkomstplac80`dist')
	mat b1 = r(table)[1,1]
	mat b2 = r(table)[5,1]
	mat b3 = r(table)[6,1]
	mat b4 = e(N)
	mat b5 = r(table)[4,1]
	loc ii = `i'+0.15
	mat b = `ii',4,b1,b2,b3,b4
	mat A = A\b
	
	loc ++i
}
	
	
****************************************************************************
****************ESTIMATING EFFECTS FOR THE RICH (LOWER PANEL OF FIGURE A26)******
********************************************************************************
if 1==1 {
	
	loc i = 1

foreach dist of global afst {
	
	****FULL SAMPLE
	xtreg redist indkomstplac80`dist' c.indkomstplac80`dist'#place_primsample indkomstplac20`dist' $ICOVAR ${ccovar`dist'} i.municip if prim_sample==1,  robust fe
	margins, dydx(indkomstplac80`dist') at(place_primsample=(4))
	mat b1 = r(table)[1,1]
	mat b2 = r(table)[5,1]
	mat b3 = r(table)[6,1]
	mat b4 = e(N)
	loc ii = `i'-0.15
	mat b = `ii',5,b1,b2,b3,b4
	mat A = A\b

	****FULL SAMPLE+CONTROL FOR SHARE OF POOR
	xtreg redist indkomstplac80`dist' c.indkomstplac80`dist'#place_primsample indkomstplac20`dist' c.indkomstplac20`dist'#place_primsample $ICOVAR ${ccovar`dist'} i.municip if prim_sample==1,  robust fe
	margins, dydx(indkomstplac80`dist') at(place_primsample=(4))
	mat b1 = r(table)[1,1]
	mat b2 = r(table)[5,1]
	mat b3 = r(table)[6,1]
	mat b4 = e(N)
	loc ii = `i'-0.05
	mat b = `ii',6,b1,b2,b3,b4
	mat A = A\b
	
	***EXCLUDING MOVERS
	xtreg redist indkomstplac80`dist' c.indkomstplac80`dist'#place_primsample $ICOVAR ${ccovar`dist'}  if prim_sample==1 & moved!=1,  robust fe
	margins, dydx(indkomstplac80`dist') at(place_primsample=(4))
	mat b1 = r(table)[1,1]
	mat b2 = r(table)[5,1]
	mat b3 = r(table)[6,1]
	mat b4 = e(N)
	loc ii = `i'+0.05
	mat b = `ii',7,b1,b2,b3,b4
	mat A = A\b

	***RESTRICTING TO SAMPLE OF RICH RESPONDENTS
	xtreg redist indkomstplac80`dist' $ICOVAR ${ccovar`dist'} i.municip if prim_sample==1 & place_primsample==4,  robust fe
	margins, dydx(indkomstplac80`dist')
	mat b1 = r(table)[1,1]
	mat b2 = r(table)[5,1]
	mat b3 = r(table)[6,1]
	mat b4 = e(N)
	loc ii = `i'+0.15
	mat b = `ii',8,b1,b2,b3,b4
	mat A = A\b
	
	
	*drop INEQ
	loc ++i
}


}

clear 
svmat A

drop in 1

	tw (scatter A3 A1 if A2==1, mc(black) ms(o)) (rspike A4 A5 A1 if A2==1,lc(black))  ///
	(scatter A3 A1 if A2==2, mc(gs5) ms(o)) (rspike A4 A5 A1 if A2==2, lc(gs5)) ///
	(scatter A3 A1 if A2==3, mc(gs9) ms(o)) (rspike A4 A5 A1 if A2==3 ,lc(gs9)) ///
	(scatter A3 A1 if A2==4, mc(gs13) ms(o)) (rspike A4 A5 A1 if A2==4, lc(gs13)) ///
	, xscal(range(0.7 9.3) extend) xlab(1 "100" 2 "150" 3 "200" 4 "250" 5 "500" 6 "1000" 7 "1500" 8 "2000" 9 "2500" ) ///
	ytit("") ysca(range(-8 8)) ylabel(-8 (4) 8) yline(0) name(FE_EXPOSURETORICH_NYE,replace) legend(position(11) ring(0)  label(1 "Main Sample")  label(3 "Controlling for Exposure to Poor Individuals") label(5 "Excluding Movers") label(7 "Sub-sample of Poor Respondents") order(1 3 5 7)) xtit("Size of Context (radius in meters)") tit("Marginal Effect of Exposure to Rich Individuals for the Poor")
	
	
	tw (scatter A3 A1 if A2==5, mc(black) ms(o)) (rspike A4 A5 A1 if A2==5,lc(black))  ///
	(scatter A3 A1 if A2==6, mc(gs5) ms(o)) (rspike A4 A5 A1 if A2==6, lc(gs5)) ///
	(scatter A3 A1 if A2==7, mc(gs9) ms(o)) (rspike A4 A5 A1 if A2==7 ,lc(gs9)) ///
	(scatter A3 A1 if A2==8, mc(gs13) ms(o)) (rspike A4 A5 A1 if A2==8, lc(gs13)) ///
	, xscal(range(0.7 9.3) extend) xlab(1 "100" 2 "150" 3 "200" 4 "250" 5 "500" 6 "1000" 7 "1500" 8 "2000" 9 "2500" ) ///
	ytit("") ysca(range(-8 8)) ylabel(-8 (4) 8) yline(0) name(FE_EXPOSURETORICH_RICH,replace) legend(position(11) ring(0)  label(1 "Main Sample")  label(3 "Controlling for Exposure to Poor Individuals") label(5 "Excluding Movers") label(7 "Sub-sample of Rich Respondents") order(1 3 5 7)) xtit("Size of Context (radius in meters)") tit("Marginal Effect of Exposure to Rich Individuals for the Rich")
	
	gr combine  FE_EXPOSURETORICH_NYE FE_EXPOSURETORICH_RICH, col(1) ysize(10) graphregion(margin(zero) color(white)) 
	gr export ".\inequalitypanel\results\illustration_exposuretorich.pdf",replace
}	
}

}


